Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 eventif( $('.target').length > 0 ) { // if target element exists in DOMif( isTargetVisble() ) { // if target element is visible on screen after DOM loadedif(_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 infoconsole.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)

Post a Comment for "Fire Ajax Call In Function Binding Window.scroll Only Once Per Conditional Check"