Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web_development

Smooth Scroll to the Top of the Page – jQuery

3.33/5 (3 votes)
13 Feb 2013CPOL1 min read 84.7K  
Create your own smooth scroll to the top button on any web page

Smooth Scroll

Smooth Scroll

When content of a web page exceeds a page and visitors scroll down the web page, then having a button to smooth scroll to the top of the page is a good idea. jQuery scroll function made it very easy to create a such a button just by writing a few lines of code. jQuery scroll function checks if the document is scrolled and is greater than a given value, then shows the scroll to top button, if the page is not scrolled or scrolled to the top of the page, then it hides the button.

By the end of this article, you will be able to create your own smooth scroll to top button on any web page.

Smooth Scroll to the Top of the Page

HTML Code

The ID of the link element will be used to show the button and scroll to the top of the page.

HTML
<a href="#" ID="backToTop"></a>

CSS Code

The CSS code is displaying the button at the bottom-center of the page.

CSS
a#backToTop {
a#backToTop {
    width:40px;
    height:40px;
    opacity:0.5;
    position:fixed;
    bottom:5px;
    left:50%;
    display:none;
    text-indent:-10000px;
    outline:none !important;
    background-image: url('top.png');
    background-repeat: no-repeat;
}

jQuery Code

The jQuery code checks if the value of the page scrolled down is greater than 50, then fadeIn() the button, when the button is clicked, then scroll the page to the top and fadeOut() then button.

JavaScript
jQuery(document).ready(function($){
    $(window).scroll(function(){
        if ($(this).scrollTop() > 50) {
            $('#backToTop').fadeIn('slow');
        } else {
            $('#backToTop').fadeOut('slow');
        }
    });
    $('#backToTop').click(function(){
        $("html, body").scrollTop(0);
        return false;
    });
});

Scrolling Smoothly

To make a smooth scroll, we will use jQuery animate function and assign the speed to scroll to the top of the page.

JavaScript
jQuery(document).ready(function($){
    $(window).scroll(function(){
        if ($(this).scrollTop() > 50) {
            $('#backToTop').fadeIn('slow');
        } else {
            $('#backToTop').fadeOut('slow');
        }
    });
    $('#backToTop').click(function(){
        $("html, body").animate({ scrollTop: 0 }, 500);
        return false;
    });
});

Resources

Demo

Scroll down the page and you will see the red up-arrow button at the bottom-center of the page.

The post Smooth Scroll To The Top of The Page – jQuery appeared first on Noor Ahmad Feroozi.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)