JavaScript Scroll to Top button

Thursday , 29, April 2021 Leave a comment

we will learn how we can scroll back to the top of the window using javascript. This situation often arises when any user has come to the end of the page and now he wants to back to the top. Here, we can show a button on click of which he will be taken back to the top of the window.

Following is the example JavaScript code .

const scrollBtn = document.querySelector('.btn-scroll');

window.addEventListener('scroll' , () =>{
    if(document.body.scrollTop > 20 || document.documentElement.scrollTop > 20){
        scrollBtn.style.display = 'block';
    }else{
        scrollBtn.style.display = 'none';
    }
});

scrollBtn.addEventListener('click', () =>{
    window.scroll({
        top: 0,
        behavior: 'smooth',
    });
});

The querySelector() method returns the first element that matches a specified CSS selector(s) ,we use for select scroll to top button. The addEventListener() method attaches an event handler to the window if you scroll window. The scrollTop property sets or returns the number of pixels an element’s content is scrolled vertically. scrollBtn a const Variable ,it is get you value of scroll to button.

When you click this scroll to button , the scrollBtn trigger window.scroll by addEventListener to scroll top.

I didn’t use anything extra in CSS . set button position and increase body height only .

<html>
<head>
    <style>
    body{
        min-height:2200px;
    }
    .btn-scroll{
        position:fixed;
        bottom:10px;
        right:10px;
    }
    </style>
</head>
<body>
<p class="btn-scroll">top</p>
<script src="script.js"></script>
</body>
</html>

Following is the example HTML and CSS code .

javaScript Resize Image Example

Leave a Reply

Your email address will not be published. Required fields are marked *