jQuery Scroll Top – Smooth Scrolling to Top of the Page

jQuery Scroll Top – When you reach the bottom of the website page that has long content then you will need to scroll back to the top of the page on a button click. To implement it, you will get the standard source code in this tutorial.

jquery scroll top

Scroll to Top in jQuery

I have implemented scroll to top in jquery with a long page and a red button is hidden on the top.  When you scroll down the page, a red button will appear at the right-bottom position. After that, you can click that button to scroll to the top of the page.

Learn Also –

Trigger Click Event on Pressing Enter Key

How to Create To-Do List using jQuery

Now, You have to configure the following steps for Smooth Scrolling to Top of the Page –

1. Create Create an HTML button

An HTML anchor tag is used to create a button. It contains two required attributes are –

  • javascript:void(0) –  It will stop to refresh the page when you click the anchor tag. click to learn it in detail
  • id="scrollTopButton" – It will be used to access the anchor tag quickly
<a href="javascript:void(0)" id="scrollTopButton">Scroll Top</a>

2.  Design HTML button with CSS

You can customize the created button using the following CSS code. Even you can add/change it according to your project design.

<style type="text/css">

#scrollTopButton {
  position: fixed;
  right: 12%;
  bottom: 10px;
  background: red;
  padding: 10px;
  font-size: 20px;
  color: #fff;
  text-decoration: none;
  opacity: 0;
  transition: all 0.4s ease-in-out 0s;
}
</style>

 

3. Scroll to the top on the button click using jQuery

  • First Include jQuery CDN to execute the custom jquery code.
  • Access the HTML button with its id and assign it to a variable scrollTopButton
  • Write a script to display or hide the red button at the bottom-right position. when you scroll down more than 100px 100px then the opacity value 1  otherwise 0 will be added to the red button.
  • Write a script on click event and use the animate() method with value scrollTop:0 & time period 500 for smooth scrolling up to 5 seconds.
<script type="text/javascript">
  
$(document).ready(function() {

  
  var scrollTopButton = $("#scrollTopButton");

  
  $(window).on('scroll',function() {
    
    if ($(this).scrollTop() > 100) {
      $(scrollTopButton).css("opacity", "1");

    } else {
      $(scrollTopButton).css("opacity", "0");
    }

  }); 

  //Click event to scroll to top
  $(scrollTopButton).on('click', function() {
    $('html, body').animate({
      scrollTop: 0
    }, 500);
    return false;

  }); 

  
}); 
</script>

 

Tutorial Summary

I hope you have understood the above jquery code. Now you can easily implement the above functionality in your project.

If you have any questions, you can ask me through the below comment box. Also, Share it with your friends so that they can also learn it.