Header Ads

ad

Animated scroll to top of a website page by using Jquery





In this article I am going to explain about how to scroll up with animation on click of a button using Jquery. Before I start, I am going to tell you the basic requirements. First of all, We need a simple web page layout, some knowledge in HTML, CSS and Jquery. Please note, if we have simple HTML pages then place the button element to anywhere but if the projects are made of many templates (like header.php, footer.php) , then we need to place the element to any of a common template (eg. footer.php). We suggest to place the element in footer.

Okay let us start with HTML.



HTML

<a href="javascript:void(0)" class="scrollTo-top">Back to Top</a>
/* Note: we have used javascript:void(0) to ensure that there will be no return type on
click of that anchor tag */

CSS

/* style the button as per your need */
.scrollTo-top 
     position: fixed; 
     bottom: 30px; 
     right: 30px; 
     display: none; 
     width: 100px; 
     height: 60px; 
     background-color: #cccccc; 
     text-align: center; 
     border-radius: 100%; 
     color: #000000; 
     font-size: 20px; 
     padding-top: 10px; 
}

JQUERY

$(document).ready(function() {
     //check whether a user scroll down
     $(window).scroll(function() {
         if($(this).scrollTop() > 200) {
             $('.scrollTo-top').fadeIn();
         } else {
             $('.scrollTo-top').fadeOut();
         }
     });

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

That's is it. Now you have a scroll to top button in your web page. Hope you liked it.
Share this post as much as you can to make others aware of Jquery scrollTop functionality.

No comments