Here’s a simple way to detect if the user has scrolled to the Top or Bottom of the page using jQuery
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Detect if User Scrolled - 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 () {
var $win = $(window);
$win.scroll(function () {
if ($win.scrollTop() == 0)
alert('Scrolled to Page Top');
else if ($win.height() + $win.scrollTop()
== $(document).height()) {
alert('Scrolled to Page Bottom');
}
});
});
</script>
</head>
<body>
<div>Page Top</div><br />
<div style="height:1200px"></div>
<div>Page Bottom</div>
</body>
</html>
Here's some explanation:
$(window).height() - returns height of browser viewport
$(document).height() - returns height of HTML document
$(window).scrollTop() – returns the current vertical position of the scroll bar.
So if the scroll bar is at the very top, the value of $(window).scrollTop() will be Zero. Similarly if the value of the browser viewport + vertical position of scroll bar = document height, then the user has scrolled to the bottom of the page.
See a Live Demo
Tweet
9 comments:
hi, nicely done. :)
Is it also possible to scroll to bottom with jquery?
Try this untested code:
$('html, body').animate({scrollTop: $(document).height()}, 900);
This is great! Is it possible to trigger another alert once the user begins scrolling up again? say if they scroll up 30px from the bottom of the page?
Working beautifully
Thanks.
Just in case anyone is having a problem getting the correct $(document).height, like I did, what I did to solve the problem was on document ready I used var doc = document.documentElement.clientHeight to get the correct height and put it in a variable, then used : if ($(window).scrollTop() >= $(window).height() - + doc + - 100) to establish the condition. I hope this helps someone.
Thanks, but having trouble getting the bottom alert to fire on iPad... Any thoughts? Top works fine. iOS6, iPad 2.
csayer: Fixed positions are not supported in version < iOS 5.
A wild guess, but try the following:
$("#yourelementtoscroll").css({ "position": "relative" });
//scroll code comes here
$("#yourelementtoscroll")css({ "position": "fixed" });
Hi
It works great the first time it triggers the function. At the trigger function I load another page with more content to the main page. And it works great.
But when I scroll down to the bottom of new content, it won´t trigger anymore. What do I do wrong?
Thanks again for a great script!
Max
Thanks ,it works great
Post a Comment