Reputation: 21
Hi I'm looking for a way to detect how many pixels a user has scrolled down a web page ( real time) before triggering events.
I've come across this code which is the type of thing I'm after, however I need to collect the whole page rather than just a div. I can't enlarge the div to the size of the entire page because it will need to scroll on iPads/iPhones etc.
<head>
<script type="text/javascript">
function OnScrollDiv (div) {
var info = document.getElementById ("info");
info.innerHTML = "Horizontal: " + div.scrollLeft
+ "px<br/>Vertical: " + div.scrollTop + "px";
}
</script>
</head>
<body>
<div style="width:100px;height:200px; overflow:auto;" onscroll="OnScrollDiv (this)">
Please scroll this field!
<div style="height:300px; width:100px; background-color:#ccc;"></div>
Please scroll this field!
<div style="height:300px; width:100px; background-color:#ccc;"></div>
Please scroll this field!
</div>
<br /><br />
Current scroll amounts:
<div id="info"></div>
</body>
An example of what i'm after can be found at http://www.nikebetterworld.com/ Any help will be much appreciated.
Edit: it's at the bottom of the page!
Upvotes: 1
Views: 238
Reputation: 337560
What you need to look for in jQuery are the scroll()
event, plus the scrollTop()
method. You can use these to discover how far down the page the user has scrolled, and based on the value display or hide content as you need.
$(window).scroll(function() {
var currentPosition = $(this).scrollTop();
// do something with currentPosition...
});
You can also apply this method to indiviual elements which have overflow: scroll
applied to them, as well as the window
object, as in this case.
Here's a fiddle to see it in action
Upvotes: 1