Vaia Vaia - 4 months ago 21
Javascript Question

Prevent calling ajax on scroll when already called

I have a plugin that tells me if an element is visible in the viewport with

$('#element').visible()
(set to
true
when visible).

Now I want to create a function that I scroll down a page and load new content with ajax. I have this so far:

window.onscroll = function() {
console.log($('#ele').visible());

if ($('#ele').visible()) {
//ajax call comes here
}

};


As soon as I see the element my log shows true:

enter image description here

I don't have problems implementing the ajax-request now, but shouldn't I block this function to occur only once? How could I prevent that a new element that already has been loaded to load again (prevent using ajax again)?

I thought of using a boolean-variable, but my problem is that I don't know how to implement that because if I set a variable, how would the browser know it's value? Because on every move of my mousewheel it cant remember what that variable's value was?

EDIT:

I tried the code of Ismail and it never reaches the ajax call (alert won't show).

window.onscroll = function() {
var ajaxExecuted = false;
var ele = $('#load_more').visible();
console.log(ele);

return function() {
if (ajaxExecuted) return;

if (ele) {
alert("OK");
var ajaxArray;
ajaxArray = { page: 2 }
ajaxLoadContent(ajaxArray, "load_more", "ajax_load");
ajaxExecuted = true;
}
}
};

Answer

You can use this:

window.onscroll = (function() {
    var ajaxExecuted = false;
    return function() {
        if(ajaxExecuted) return;

        if ($('#ele').visible()) {
               $.ajax({...}).success(function() {
                   //Your code here;
                   ajaxExecuted = true;
               });
        }
    }
})();
Comments