Scroll to Top using jQuery



In this tutorial I will explain how to implement Smooth Scroll to Top functionality using jQuery. This feature helps user to move quickly top of the page.

I will explain this with a simple example. In this example the scroll to top button will appear, when user scroll the page more then 300px.

HTML Part:
Following is the HTML part.

<html>
<head>
  <title>Scroll to top</title>
<head>
<body id="top">
  <div class="wrap">
  <h3>Scroll to Top</h3>
  <!-- content of the page -->
  </div>
  <div id="back-top"><!-- scroll top button -->
    <a href="#top"><span></span>Back to Top</a>
  </div>
</body>
</html>

CSS Part:
Now add following CSS for Back to Top Button.

.wrap{ margin:20px auto; width:85%; }
p{ text-align:justify; }  

#back-top {
  position: fixed;
  bottom: 30px;
  right: 40px;
}
#back-top a {
  width: 65px;
  display: block;
  text-align: center;
  font: 10px/100% Arial, Helvetica, sans-serif;
  text-transform: uppercase;
  text-decoration: none;
  color: #DE2A05;
  -webkit-transition: 1s;
  -moz-transition: 1s;
  transition: 1s;
}
#back-top a:hover {
  color: #ccc;
}

/* arrow icon*/
#back-top span {
  width: 65px;
  height: 64px;
  display: block;
  margin-bottom: 3px;
  background: #eee url(scroll-top.png) no-repeat center center;
  -webkit-border-radius: 15px;
  -moz-border-radius: 15px;
  border-radius: 15px;
  -webkit-transition: 1s;
  -moz-transition: 1s;
  transition: 1s;
}

jQuery Script Part:
Put below script in your page for show scroll top button and scroll to top animation on click of this button.

$(function() {
  var btn = $('#back-top');
  // Hide scroll top button
  btn.hide();

  $(window).on('scroll', function(){
    // if you scroll more then 300px then fadein goto top button
    if ($(this).scrollTop() > 300) {
	btn.fadeIn();
    } else {
	btn.fadeOut();
    }
});

  // Animated scroll to top
  btn.on('click', function(){
    $('html,body').animate({
      scrollTop: 0
    }, 800 );
    return false;
  });
});

Live Demo


Download Code

Hope this will help you to add Scroll to Top feature in your website.