Use jQuery to Scroll to Bottom or Top of a Page

I had recently written about how to Use jQuery to Detect if User has Scrolled to the Bottom or Top of a Page. A DevCurry.com reader commented asking if it was also possible to use jQuery to scroll to the bottom of a page.

Here’s the solution

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Scroll to Bottom or Top - DevCurry.com</title>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
</
script>
<
script type="text/javascript" language="javascript">
$(function () {
$('#scrlBotm').click(function () {
$('html, body').animate({
scrollTop: $(document).height()
},
1500);
return false;
});

$('#scrlTop').click(function () {
$('html, body').animate({
scrollTop: '0px'
},
1500);
return false;
});
});
</script>
</
head>
<
body>
<
a id="scrlBotm" href="#">Scroll to Bottom</a>
<
div style="height:1000px"></div>
<
a id="scrlTop" href="#">Scroll to Top</a>
</
body>
</
html>

In the code above, we achieve the scrolling by manipulating the vertical position of the scroll bar, using scrollTop. On the ‘Scroll to Bottom’ link click, we set scrollTop to the height of the HTML document, so the scroll goes to the bottom of the page. Similarly, on the ‘Scroll to Top’ link, we set scrollTop to 0px, so the scroll goes to the top of the page.

Also by using return false, we are preventing the scroll to jump to the top, and then return back to animate the scroll.

See a Live Demo

Note: You can also check the jQuery ScrollTo() plugin for additional features.

11 comments:

  1. It will not work in all browsers because getting the document height differs between firefox and IE

    ReplyDelete
  2. fine... its working well and acting smoothly....

    ReplyDelete
  3. A simple clean script that does work in modern browsers including Firefox and IE. Well done

    ReplyDelete
  4. Could you use event.preventDefault() instead of "return false"?

    ReplyDelete
  5. Is is possible to initialize this one with Ajax some how? Maby LiveQuery? But how? :D


    Thanks! / Jonni

    ReplyDelete
  6. thanks, quick and simple solution...

    ReplyDelete
  7. Thank you!

    I'll be using this alot.

    ReplyDelete
  8. Hi,


    I'm not able to do smooth scrolling on my web page. I used master page for header n footer section. and in inner page 'm writing the jquery. Plz help me out.

    ReplyDelete