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.
Tweet
11 comments:
so smooth...
nice trick, thanks ^^
It will not work in all browsers because getting the document height differs between firefox and IE
fine... its working well and acting smoothly....
A simple clean script that does work in modern browsers including Firefox and IE. Well done
Could you use event.preventDefault() instead of "return false"?
Is is possible to initialize this one with Ajax some how? Maby LiveQuery? But how? :D
Thanks! / Jonni
thanks, quick and simple solution...
Thank you!
I'll be using this alot.
thanks for you share
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.
Thank you!
Post a Comment