Create Scroll to Top button using JavaScript

Create Scroll to Top button using JavaScript

In this post, we will learn how to create a scroll to the top button using Javascript.

The Scroll to Top button helps a user to quickly navigate to the top of the page with just one click of a button. This gives the site a better user experience when reading a long post on the page.

To scroll to the top of a page we will use the window.scroll() method. This method will get triggered when we click the "Goto Top" button on our web page.

Let's create a button to scroll to the top once a user reaches the end of the page with vanilla Javascript.

HTML Code:

    <a href="" class="btn" id="top">Goto Top</a>

Here, we have some HTML content on the page and <a> (anchor) tag at the bottom of the page. The anchor tag (<a>) will be used as a button for a user to click. You can also use a button instead of the <a>. The a element has an id equal to top.

We have also added some CSS to give some styling to the <a> tag to make it look like a button.

.btn {
      padding: 20px;
      background: green;
      color: white;
      width: 100%;
      display: inline-block;
      text-align: center;

Next comes the JavaScript part, we have coded the script like this.

    let gotoTop = document.querySelector("#top");
    gotoTop.addEventListener("click", (e) => {
      window.scroll({ top: 0, left: 0, behavior: "smooth" });

Here, we have selected the button i.e the <a> tag using document.querySelector().

Next, we have added an click event listener, that will trigger the callback function once the button is clicked.

The window.scroll() is used to scroll the window to a particular position on a web page.



Here, since we want to scroll to the top of the page we have set the top and left positions to 0 and for smooth scrolling, we have set the behavior to smooth.

window.scroll({ top: 0, left: 0, behavior: "smooth" })

Read More Window.scroll() - Web APIs | MDN

scroll to top button javascript

Demo Code:

Edit scroll-to-top-javascript

Related Topics:

JavaScript - Show and hide div on button click using JavaScript

How to display JavaScript variable value in HTML

Copy text from an HTML element to clipboard-JavaScript

Change image source (src) on hover using CSS

Change Text Color Using JavaScript with Example