Animated Scroll to Top with jQuery

In this tutorial we’re going to take a look at the creation of an animated scroll to top with jQuery. As the name says, we’ll be create a button, that appears in the bottom right corner after the visitor starts scrolling on our website. If he/she clicks this button, the page will scroll back to the top. We’ll use a smooth scrolling animation, that starts slow, speeds up and when it’s almost at the top, it’s slows down again.

To get us started, we need to have the jQuery library added to our project. We’ll use google’s hosted version:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

After this, we need to create the button, a simple anchor tag, with a class.

<a href="#" class="scrollToTop"></a>

Now, that we have our button, we need to position and style it. Here’s the arrow I use as background image. Downlaod

We’ll give the button a 40px width and height, position absolute, display none so it’s hidden by default, and bottom, right 20px; This will position it in the bottom right corner.

.scrollToTop{
    width:40px;
    height: 40px;
    background-image: url('arrow.png');
    position:fixed;
    right:30px;
    bottom:30px;
    display:none;
}

And we have our button. But it’s not functional yet. To make it appear as we scroll down, and then to return us to the top of the page, we need a bit of jQuery. Two functions actually.’

The first one will check if we scrolled down or not, and if yes, it displays the button, and if we manually scroll up, it’ll hide it. It’ll also hide if we clicked the button to scroll to the top.

//Check to see if the window is top if not then display button
$(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }
});

Then the second one, to return us to the top of the web page, when we click the button.

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

Here’s it all put together in case u just want to copy and paste:

$(document).ready(function(){
    //Check to see if the window is top if not then display button
    $(window).scroll(function(){
        if ($(this).scrollTop() > 100) {
            $('.scrollToTop').fadeIn();
        } else {
            $('.scrollToTop').fadeOut();
        }
    });
    //Click event to scroll to top
    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
    });
});

And we’re done! I hope this tutorial helped you add an awesome animated scroll to top with jQuery, if yes, please do share it with your friends and followers!