2

I'd like to employ some infinite scrolling to get rid of the pagination on my site. However, this scroll function I've found seems to have some quirks. It appears to fire when scrolling up, for one. Is there a way to only fire a scroll event when scrolling down? Also, it seems that if there is no scroll bar, it doesn't not fire at all, like it's tracking the movement of the page, rather than if a mousewheel or arrow or spacebar is being pressed. Any good scroll detection functions?

$(window).scroll(function () {

    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {

        //infinite scrolling is the idea

    }

});

Thanks!

1252748
  • 14,597
  • 32
  • 109
  • 229
  • possible duplicate of [Differentiate between scroll up/down in jquery?](http://stackoverflow.com/questions/4989632/differentiate-between-scroll-up-down-in-jquery) – Felix Kling Aug 14 '12 at 23:39
  • @FelixKling looking at the accepted answer for that, would I declare said variable globally? Is there a special way I should do that? I've never used a global variable as I've read many, many times that they are sort of dark side-ish.. thanks! – 1252748 Aug 15 '12 at 01:54
  • It does not have to be global, just somewhere where it is accessible from your `scroll` event handler, e.g. if you bind the handler inside the `ready` handler, then declare the variable there. – Felix Kling Aug 15 '12 at 02:12
  • @FelixKling okay that makes sense. just capture where it is at the very beginning of the function. do people usually attach timers to these so the scroll only fires every 100ms or so? – 1252748 Aug 15 '12 at 02:34
  • Yes, it is called debouncing, have a look at http://benalman.com/projects/jquery-throttle-debounce-plugin/. – Felix Kling Aug 15 '12 at 03:48

1 Answers1

5

The formula you were looking for is this

document.body.scrollTop >= (document.body.scrollHeight - window.innerHeight - 50)

This assumes that your body element actually has no set height and that it's overflow is not set to hidden or scroll.

This would also work on scroll up though as long as you;re inside the 50 pixel threshold. You could however save the previous scroll offset and only do something if it increased.

var lastScrollTop = 0;
$(window).scroll(function(e) {
    var body = $("body")[0],
        scrollTop = body.scrollTop;

    if (scrollTop > lastScrollTop) {
        if (scrollTop >= (body.scrollHeight - window.innerHeight - 50)) {
            // do something
        }
    }
     lastScrollTop = scrollTop;
});
Torsten Walter
  • 5,614
  • 23
  • 26