Scroll to the bottom of a page with jQuery

Posted in Javascript -

Some time back I posted how to scroll to the top of a page with jQuery and was recently asked how to scroll to the bottom of a page with jQuery. I took a punt on the answer and posted it in the comments without testing it and the commenter said it didn't work, so I tested it out for myself and my solution did work. I present it here along with a link to a full working example which shows scrolling to the bottom and scrolling to the top.

The Javascript

The following Javascript will scroll the page to the bottom using jQuery:

$('html, body').animate({scrollTop:$(document).height()}, 'slow');

Obviously you can change the animation speed ('slow' in the above example) to something else such as 'fast' or a numeric duration in milliseconds where the higher the number, the slower the animation.

To bind the scrolling function to a click done on an existing element in the page, do something like this, where #someID is the element's ID:

$(document).ready(function() {
   
    $('#someID').click(function(){
        $('html, body').animate({scrollTop:$(document).height()}, 'slow');
        return false;
    });

});

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

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.



Related posts:


Comments