简体   繁体   中英

fire ajax call in function binding window.scroll only once per conditional check

I am having this fiddle which detects if targeted div is in the viewport. However if I want to fire only one ajax call when the DOM element is in the viewport (instead of multiple times). How could I make this happen?

if( isTargetVisble() ) { // if target element is visible on screen after DOM loaded
    $('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info
    alert('this is going to be the ajax call')
} else {
    $('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
}

It is firing multiple alert() right now as it is binding to window.scroll . How could I just fire one when it becomes visible?

Keep track of the visible state of the target with a variable. On each scroll, compare the new value of isTargetVisble() with the old.

var _alreadyVisible = false;
$(window).scroll(function(){ // bind window scroll event
    if( $('.target').length > 0 ) { // if target element exists in DOM
        if( isTargetVisble() ) { // if target element is visible on screen after DOM loaded
            if(_alreadyVisible){
                //ignore the scroll
            } else {
                //the target just became visible
                _alreadyVisible = true;
                console.log('target became visible')
                $('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info
            }
        } else {
            if(_alreadyVisible){
                //the target was just hidden
                _alreadyVisible = false;
                $('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
                console.log('target became invisible')
            } else {
                //ignore
            }
        }
    }
});

See this fiddle (bring up the console with F12 and notice how there is only a log when the target changes visibility, not on every scroll)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM