A simple 'Scroll to Top' Script

January 14, 2013

Somebody asked me about the “Back To Top” icon that appears in the lower right corner if you scroll down a page on this website. Clicking on the icon will scroll the window back to the top, a handy feature if you have long pages.

If you are not familiar with icon fonts you may want to review my posts Icon Fonts and Icon Fonts and Drupa 7 before continuing.

Here is the code:

HTML

First we add the scroll icon in the page footer.


<a id="toTopButton" href="#toTop"><i class="icon icon-arrow-up"></i></a>

CSS

Now we position the icon at the lower right corner of the browser window. Then we add a hover behavior by varying the opacity of the icon.


#toTop { 
    display: block; 
    position: fixed; 
    bottom: 20px; 
    right: 20px; 
    transition: all 0.5s ease 0s; 
    opacity: 0.5; 
    cursor: pointer; 
} 
#toTop:hover { 
    opacity: 1; 
}

Javascript

The comments in the script tell the story. Here is what we do:

  • Check if a ‘#toTop’ icon is present in the DOM
  • Attach a click event handler to the ‘#toTop’ icon. Whenever the icon is clicked the browser window will scroll back to the top
  • Hide the ‘#toTop’ icon if we are at the top of the browser window. You might expect to use the scrollTo() method of the window object. It is supported by all modern browsers, except that IE8 returns always 0. Turns out that the behavior is different between various browsers. I found the following return values for scrollTop():
      $(window).scrollTop() $('html').scrollTop()
    Firefox value value
    Webkit value 0
    IE8 0 value
    IE9+ value value
  • Whenever we detect scrolling we show the ‘#toTop’ icon.
  • Whenever we detect that the window is resized we update the ‘#toTop’ icon visibility.
  • Note: Scrolling to the top uses the easing plugin by George McGinley Smith. Download is available at: http://gsgd.co.uk/sandbox/jquery/easing/

if($('#toTop').length) { 
    // click function for the scroll to top icon 
    $('#toTop').click( function () { 
        $('window, html').animate({scrollTop:0}, 500, 'easeOutCubic'); 
    }); 
    // hide scroll icon if content is at top already 
    if ($(window).scrollTop() === 0 && $('html').scrollTop() === 0) { 
        $('#toTop').hide(); 
    } 
    // update scroll icon if window is resized 
    $(window).resize(function () { 
        if ($(window).scrollTop() === 0 && $('html').scrollTop() === 0) { 
            $('#toTop').hide(); 
        } 
    }); 
    // update scroll icon when scrolling 
    $(window).scroll(function () { 
        if ($(window).scrollTop() === 0 && $('html').scrollTop() === 0) { 
            $('#toTop').fadeOut(400); 
        } else { 
            $('#toTop').fadeIn(400); 
        } 
    }); 
}