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.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

11 comments:

Beben Koben said...

so smooth...
nice trick, thanks ^^

Anonymous said...

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

callezee said...

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

Wayne said...

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

Anonymous said...

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

Jonni said...

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


Thanks! / Jonni

xrei said...

thanks, quick and simple solution...

Mark said...

Thank you!

I'll be using this alot.

Software akuntansi laporan keuangan terbaik said...

thanks for you share

Rohith_JoY said...

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.

Anonymous said...

Thank you!