no longer in view js 1

no longer in view js

function onVisibilityChange(el, callback) {
    var old_visible;
    return function () {
        var visible = isElementInViewport(el);
        if (visible != old_visible) {
            old_visible = visible;
            if (typeof callback == 'function') {
                callback();
            }
        }
    }
}

var handler = onVisibilityChange(el, function() {
    /* Your code go here */
});


// jQuery
$(window).on('DOMContentLoaded load resize scroll', handler);

// Non-jQuery
if (window.addEventListener) {
    addEventListener('DOMContentLoaded', handler, false);
    addEventListener('load', handler, false);
    addEventListener('scroll', handler, false);
    addEventListener('resize', handler, false);
} else if (window.attachEvent)  {
    attachEvent('onDOMContentLoaded', handler); // Internet Explorer 9+ 🙁
    attachEvent('onload', handler);
    attachEvent('onscroll', handler);
    attachEvent('onresize', handler);
}

Here is what the above code is Doing:
1. We create a function called onVisibilityChange that takes two arguments:
1. el: The element to watch for visibility changes.
2. callback: The function to call when the element is visible or hidden.
2. We create a variable called old_visible and set it to undefined.
3. We return a function that does the following:
1. Check if the element is visible.
2. If the element is visible and old_visible is undefined, set old_visible to true and call the callback function.
3. If the element is visible and old_visible is true, do nothing.
4. If the element is visible and old_visible is false, set old_visible to true and call the callback function.
5. If the element is not visible and old_visible is undefined, set old_visible to false and call the callback function.
6. If the element is not visible and old_visible is true, set old_visible to false and call the callback function.
7. If the element is not visible and old_visible is false, do nothing.
4. We create a variable called handler and set it to the return value of onVisibilityChange.
5. We add an event listener to the window object that calls the handler function when the DOMContentLoaded, load, resize, and scroll events are fired.

Similar Posts