Ivijan Stefan Stipić
Ivijan Stefan Stipić

Reputation: 6668

jQuery - One trigger per each certain scroll position

This is little hard to explain. I have issue with infinite scroll function. When I scroll down my content, on certain scroll position I call one function to load my content on page. Here is that function:

var page = 1,
    total = 10; // example
$(window).on("scroll", function() {
    var search = $(document).scrollTop(),
        position = ($(document).height() - (($(".footer").height() * 2) - 50) - $(".page-heading").height() - $(".page-footer").height() - $(".navbar-toalc").height());
    if (search > position && page <= total) {
        triggerLoad(page);
        console.log(page);
        page++;
    }
});

When i get certain scroll point, I trigger function triggerLoad() where is function for ajax call and hide button on last page. That part work nice.

PROBLEM:

Function above immediately made loop of all pages. I need something to delay that loop until load new content, measure the page and waiting until I scroll on new position. Measuremant works fine but until load content I have arround 8 scroll calls and that made a loop.

Upvotes: 0

Views: 136

Answers (1)

Sabaz
Sabaz

Reputation: 5282

A very easy way is to "check" if you are already executing the triggerLoad

For example with a class to the page which says it's loading, or maybe using a boolean variable as true while loading and then reset at false with a callback function to the ajax complete

var page = 1,
    total = 10,  // example 
    isLoading = false;     // <<-------

$(window).on("scroll", function() {
    var search = $(document).scrollTop(),
        position = ($(document).height() - (($(".footer").height() * 2) - 50) - $(".page-heading").height() - $(".page-footer").height() - $(".navbar-toalc").height());
    if (search > position && page <= total && isLoading === false) {
        isLoading = true;  
        triggerLoad(page, function(){ isLoading = false; });
        console.log(page);
        page++;
    }
});

Remember to add the callback function as complete callback of your ajax

function triggerLoad(_page, _callback){
    // ...

    $.ajax({
        // ...
        complete: _callback
    });

    // ...
}

it's not a very clean solution but should work fine

Upvotes: 1

Related Questions