I’m trying to do some pagination when user scrolls to the bottom of the page, more content loads. Is there a way to get to say almost to the bottom of the page? Like maybe 1/3 from the bottom of the page?
$(window).scroll(function(){
if ($(window).scrollTop() == ($(document).height() - $(window).height())/3)
{
alert('test');
}
// ...
This doesn’t do anything
But if I delete that 3 in the code, alert pops when I get at the bottom (dead end, cant scroll anymore). But I want the alert to show when I’m almost to the bottom.
The problem is:
Try this – http://jsfiddle.net/y7Am2/:
But I recommend you use a specific pixel value from the bottom rather than a fractional value from the top. Base it on the height of your footer (a simple hand-tweaked value, or calculated).
Your content might not be constant height. If not, and you use a fractional value, you will scroll to what seems like an arbitrary part of the page and the loading will queue. This will make your website seem unpredictable, or possibly less responsive if users are used to it loading earlier on longer pages.
So do something like this instead – http://jsfiddle.net/PwZ4D/:
Also note that as currently implemented your event will keep firing every time you scroll around at the bottom of the page. This will queue up a whole ton of AJAX calls. You probably should unbind
scrollinside your event, then rebind it when your ajax call finishes successfully.And be careful to handle cases where you have little to no content. If a page is empty or there is only enough data to fill one screen, it could keep re-querying the server needlessly if you do things wrong.
Edit:
Per request, you unbind the
scrollevent with code like this – http://jsfiddle.net/5vXJ5/:Edit:
Again per request, you rebind it the same way you bound it to begin with. However, since you end up with self-referential code you’ll need to name your function. The final code might look something like this:
This is just an example though. You’ll have to tweak it to your specific scenario.