Scroll to Top Using jQuery (Setup time: 2mins)

Sam Deering
Share

This is a quick step by step to setup a scroll to top for your website. For a demo, just scroll down on this site.

1. Download scrollTo plugin, include it.
2. Get an image (arrow or such).
3. Include some HTML below.
4. Include some jQuery/JavaScript below to catch window scroll and handle display of image.
5. Thats it!

HTML


scroll to top

jQuery

Just some a little jQuery to show the image when the user scrolls down and hide when they scroll up, and handle the click event.

$(document).ready(function()
{
    var $scrollTop = $('#scroll-to-top');

    $(window).scroll(function()
    {
        //scroll top top
        if ($(this).scrollTop() > 100)
        {
            $scrollTop.fadeIn(1000);
        }
        else
        {
            $scrollTop.hide();
        }
    });

    $scrollTop.bind('click', function(e)
    {
        e.preventDefault();
        $.scrollTo(0, 1000);
    });
});

Note: If you want a cross browser solution just use this:

window.scrollTo(0,0); //chrome scroll to top bugfix

CSS

Just some simple CSS to handle showing of image and cross browser opacity.

#scroll-to-top {
    position: fixed;
    bottom: 10px;
    right: 10px;
    display: none;

    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=50);
    -moz-opacity: 0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
}
#scroll-to-top:hover {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
    -moz-opacity: 1.0;
    -khtml-opacity: 1.0;
    opacity: 1.0;
}