AlexioVay
AlexioVay

Reputation: 4527

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

Upvotes: 0

Views: 136

Answers (2)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

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

Upvotes: 1

Jordan Kuhn
Jordan Kuhn

Reputation: 103

One easy solution: set a boolean to true when the element first becomes visible and set it to false when it stops being visible. Only fire the request if those states mismatch (i.e. if it's visible but the boolean is false - that means it's the first time you've seen the window. You'd then set the bool afterwards so it won't fire off anymore until it disappears and reappears again).

Upvotes: 1

Related Questions