Create a smooth scroll to top button in jQuery

On many of the websites, you may find that after scroll to a certain length towards bottom a fixed button appears. This is the scroll to top button.

In most of the cases, it appears on the bottom right part of the web page. Clicking this button will send you to the top of the web page. The main purpose of this button is to make it easier to go back to the top part for users.

Today in this tutorial, I am going to show you how to create a smooth scroll to top button in jQuery.

Let’s start our tutorial step by step.

 

Code snippets for our smooth jQuery scroll to top button

First of all, let’s create our button. Below is our HTML code:

<div id="scrollTop">Go Top</div>

Now below is the CSS code to give our button some style and to keep it always at the bottom right position:

#scrollTop {
  position: fixed;
  bottom: 8px;
  right: 6px;
  height: 22px;
  width: 65px;
  background-color: #777;
  color: #fff;
  text-align: center;
  padding: 6px;
  cursor: pointer;
}

We have set the CSS position property to fixed so that it will be always be fixed to the bottom right corner.

Now below is our jQuery code that will do the main task:

$(document).ready(function(){
  $("#scrollTop").hide();
  $(function scrollTop() {
    $(window).scroll(function () {
      if ($(this).scrollTop() > 350) {
        $('#scrollTop').fadeIn();
      } else {
        $('#scrollTop').fadeOut();
      }
    });

    $('#scrollTop').click(function () {
      $('body,html').animate({
        scrollTop: 0
      }, 1000);
      return false;
    });
  });			
          
  
});

In the above jQuery code, we have made our button hidden when the user will be between 350 pixels distance from the top. Then if the user scrolls to the bottom from 350 pixels than the button will appear. We have used the jQuery fadeIn() and fadeOut() method to hide and show our button.

 

Also, read:

 

If you test our code on your browser then you will able to see the scroll to the top button after you scroll your mouse to the bottom to a certain distance (350 pixels in this example).

After you click the button, you will automatically be taken to the top of the page.

Here in this tutorial, I have used the jQuery animate() method to improve the user experience. With animate() method, you can see the page scroll to top smoothly that looks great.

 

So, you have seen how I have created a smooth scroll to top button in jQuery in an easy way.

Leave a Reply

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