maxbeaudoin
maxbeaudoin

Reputation: 6976

What's the most efficient way to end an infinite-scroll when running out of content?

We have a web application where we automatically load more content when we reach the bottom of the page like so:

$window
.on('scroll', function () {
    var 
        $this = $(this)
    ;
    if ($this.scrollTop() == $document.height() - $window.height()
        && $('#product-list').hasClass('has-more')) {
        // load more content
    }
})

We currently use a 'has-more' class on a parent element that is removed when there's no more content available.

I'm not quite satisfied with the approach, any idea?

Upvotes: 0

Views: 831

Answers (2)

simplyharsh
simplyharsh

Reputation: 36373

Rather than removing the class has-more when there are no other contents and (yet still) keep on checking its existence on scroll event, why not remove the event handler itself?

That way you have no event handlers and no decision making, until you bind it again, when some other ajax event tells you there are contents available now.

Upvotes: 1

Marshall
Marshall

Reputation: 4766

You could set & check a variable in scope. So your example would be something like:

!function() {
    var hasMore = true;

    $window.on('scroll', function () {
        var $this = $(this);

        if ($this.scrollTop() == $document.height() - $window.height() && hasMore) {
            // load more content & set hasMore to false if applicable 
        }
    })
}();

Only issue here is setting hasMore on pageload. Instead of doing what I did (putting it in a self-executing function) you could write hasMore in the footer. That's up to you.

This method would avoid overloading a class name as boolean, and would save you the cost (though it's insanely small) of querying the DOM.

Upvotes: 1

Related Questions