How to Add Smooth Page Scroll to Top using jQuery

You would have come across websites that provide an easy way to scroll to the top of the webpage as you move down the page, its really a good idea if the webpage is long and you want to provide a better user experience. In this article, we will show you how to add a smooth scroll to top effect using jQuery.

We will create a button on the footer of the page which when clicked will scroll the page to the top smoothly, we will use css to postion the button at a fixed position on the bottom right of the page and jQuery to provide the scrolling effect and make the button visible only if the page is scrolled down, instead of being always visible.

Step 1: Add button link
Place the following code just before the closing </body> HMTL tag


<a href="#" id="scrolltotop" title="Back to top">Back to top</a>

We will be using an image icon with upward arrow to display a back to top button. In this example we are using a 40x40px icon.

Step 2: Add the following CSS to your stylesheet file.


#scrolltotop {
height: 40px;
width: 40px;
opacity: 0.3;
position: fixed;
bottom: 50px;
right: 100px;
text-indent: -9999px;
display: none;
background: url('top_icon.png') no-repeat;
}

‘text-indent’ has been used to hide the text “Back to top” and the button position has been fixed at 100px from right and 50px from the bottom.

‘display:none;’ is used to hide the button initially.

Step 3: Now add the following jQuery code to your js file


jQuery(document).ready(function($){
$(window).scroll(function(){
if ($(this).scrollTop() < 200) {
$('#scrolltotop') .fadeOut();
} else {
$('#scrolltotop') .fadeIn();
}
});
$('#scrolltotop').on('click', function(){
$('html, body').animate({scrollTop:0}, 'fast');
return false;
});
});

Here is an explanation of the above code.

The following code makes the button visible when the page has been scrolled down.


$(window).scroll(function(){
if ($(this).scrollTop() < 200) {
$('#smoothup') .fadeOut();
} else {
$('#smoothup') .fadeIn();
}
});

The ‘.scrollTop()’ returns the current vertical position of the scroll bar. If it is greater than 200px, it fades in the “#scrolltotop” button, otherwise fades out. So, when we scroll down the page more than 200px, the button should fade in, and if scroll up to the height of less than 200px it should fade out.

The following code provides the scrolling to the top smoothly functionality.


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

The scrollTop:0 scrolls to the very top of the page, at 0px position and ‘fast’ is the duration of animation.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings ‘fast’ and ‘slow’ can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

Comments

Leave a Comment

Back to top