Home / Scroll to the top of a webpage with jQuery

Scroll to the top of a webpage with jQuery

This post shows a simple way to make anchor tags with e.g. href="#top" scroll to the top of the webpage when clicked using jQuery. Note as per the comment by Jono you can use the id of an element to scroll to. Have a read through this post then a look at his comment.

The Javascript

The following Javascript will change all <a href="#top"> links to scroll to the top instead of the instant jump that normally happens when the link is clicked.

$(document).ready(function() {
   
    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });

});

Note the "return false;" line. This is required otherwise the default action will be done and the instant scroll will happen instead of the nice animated scrolling effect.

The position the document is scrolled to can be different by changing the scrollTop value, the speed by changing the ‘slow’ value and what appears in the href by chaging the #href value.

Note that an <a name="top"></a> anchor should still be present in the page for browsers that do not have Javascript on or support jQuery.

The HTML

<a name="top"></a>
...
<a href="#top">Back to top</a>

The <a name="top"> does not have to be present, but see the note above about supporting browsers without Javascript on etc.

Why not just use a # anchor link?

You could just link to an anchor tag e.g. <a href="#someID"> and <div id="someID"> but by using jQuery you can have a smooth animation instead.

Browser versions supported

This technique works in all modern browsers. I tested in a number of browsers including IE6 and FF1 using the HTML 5 DOCTYPE.

jQuery version requirements

jQuery 1.2 or higher is required. I’ve tested this in 1.2, 1.2.6, 1.3.2, 1.4.4, 1.5.2, 1.6.2

Scroll to the bottom of a page

The technique is exactly the same for scrolling to the bottom of a page, but scroll to the height of the document instead. I’ve covered how to do this in the post Scroll to the bottom of a page with jQuery.

Working example

Click through here to a full working example which shows scrolling to both the bottom and top of the page. View the source of that page to get the full HTML required.