Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top