entropia
10/4/2017 - 11:29 AM

Is on Screen

This function checks if an HTML element is seen on screen. The threshold is set in the function as x, y. The set example is 0.7 (70%)

//Function isOnScreen with x,y == 0.7 default (70% of the images visible)
jQuery.fn.isOnScreen = function(x, y){
    
    if(x == null || typeof x == 'undefined') x = 0.7;
    if(y == null || typeof y == 'undefined') y = 0.7;
    
    var win = jQuery(window);
    
    var viewport = {
        top : win.scrollTop(),
        left : win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();
    
    var height = this.outerHeight();
    var width = this.outerWidth();
 
    if(!width || !height){
        return false;
    }
    
    var bounds = this.offset();
    bounds.right = bounds.left + width;
    bounds.bottom = bounds.top + height;
    
    var visible = (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
    
    if(!visible){
        return false;   
    }
    
    var deltas = {
        top : Math.min( 1, ( bounds.bottom - viewport.top ) / height),
        bottom : Math.min(1, ( viewport.bottom - bounds.top ) / height),
        left : Math.min(1, ( bounds.right - viewport.left ) / width),
        right : Math.min(1, ( viewport.right - bounds.left ) / width)
    };
    
    return (deltas.left * deltas.right) >= x && (deltas.top * deltas.bottom) >= y;
};

//Example Function call to see if an HTML element is visible on Screen on Scroll
jQuery(document).ready(function() {
	jQuery(window).scroll(function(){
        if (jQuery('#HTML_ELEMENT').isOnScreen()) {
            //do something
        } else {
            //do something else
        }
    });
});