views:

22

answers:

2

Hi,

Currently, I use the following logic to auto-load new posts from the database when the user reaches the bottom of the site:

$(window).scroll(function() {
 if ($(window).scrollTop() == $(document).height() - $(window).height()) {
  last_msg_funtion();
 }
});

Fair enough. It does what it's supposed to do, but I'd like to change this so it starts loading new posts when the user is e.g. 100 pixels from the bottom of the site. Any ideas? When I've tried changing the code, I've either:

** entered an almost endless loop of last_msg_function() calls, because the if() statement matches e.g. from 100 pixels away from the bottom and for every pixel down to 0 pixels when scrolling. So, if you scroll real slow, you'll maybe manage to stop at exactly 100 pixels from the bottom, but that's not going to work in real life.

**) it has to match exactly the pixels from the bottom I define, e.g. 90 pixels. If you stop scrolling at e.g. 89 or 91 pixels, it won't load anything.

So, what should I change to make sure it starts loading when you're 0 -> 100 pixels away from the bottom of the site, but at the same time not send a new request every time to change the scroll position a few pixels in any direction while it's still loading?

Thanks!

+1  A: 

You can just change your check a bit, like this:

$(window).scroll(function() {
 if ($(window).scrollTop() > ($(document).height() - $(window).height() - 100)) {
  last_msg_funtion();
 }
});

You can give it a try here. This is checking that the scroll position is 0-100px from the actual bottom...you may want to ensure that last_msg_function() doesn't do anything if it's already loading (you should do this anyway), but other than that, the if() is the only change needed.

Nick Craver
+1  A: 

Good answer Nick. One other thing to do is to make sure that your scroll function only fires once every time you user scrolls, otherwise, as you mentioned, the last_msg_function will be called multiple times. Try something like this...

var processScroll = true;
$(window).scroll(function() {
    if (processScroll  && $(window).scrollTop() > $(document).height() - $(window).height() - 100) {
        processScroll = false;
        last_msg_funtion();
        processScroll = true;
    }
});
Daniel Dyson
Thanks for the tips. I couldn't get it to work with the exact approach you suggested (no idea why), but by moving the logic into the method it calls and adding a timeout (as suggested by http://learninglamp.wordpress.com/2010/01/30/endless-scrolling-with-jquery/), it seems to work fine :-)
EspenA