1252748
1252748

Reputation: 15362

event on scroll down

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!

Upvotes: 2

Views: 6308

Answers (1)

Torsten Walter
Torsten Walter

Reputation: 5782

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;
});

Upvotes: 5

Related Questions