When Is A HTML Element Off Of The Screen

By looking at the displayed screen size and the position of the corners of an element we can check to see if it is off of the page and no longer visible.

The margin is the number of pixels that you want to clear the edge by.

Example (isOffScreen.js):


function isOffScreen(sel,margin) {
	if ( typeof margine === "undefined" ) margin = 0;

	var it = $(sel);
    var itTop = it.offset().top;
    var itBot = itTop + it.height();

	var w = $(window);
    var wTop = w.scrollTop();
    var wBot = wTop + w.height();

    return ! ( (itTop >= (wTop-margin)) && (itBot <= (wBot+margin)) );
}




There are a pair of jQuery components that encapsulate checking if an element is visible. Waypoints provides both vertical and horizontal checking. Apear is a little simpler to use. It also provides events when things disappear off of the page.

One problem that I ran into was elements that were too large to completely fit on the page. Checking to see if the element was partially on the page and if it is too large solved this.

Example (isPartiallyVisible.js):


function isPartiallyVisible(sel,margin) {
	if ( typeof margine === "undefined" ) margin = 0;

	var it = $(sel);
    var itTop = it.offset().top;
    var itBot = itTop + it.height();

    if (!it.is(':visible')) {
      return false;
    }

	var w = $(window);
    var wTop = w.scrollTop();
    var wBot = wTop + w.height();

    return (
		   (itTop >= (wTop+margin)) && (itTop <= (wBot-margin))
		|| (itBot >= (wTop+margin)) && (itBot <= (wBot-margin))
	);
}




Example (isTooBigToSeeCompletely.js):


function isTooBigToSeeCompletely(sel,margin) {
	if ( typeof margine === "undefined" ) margin = 0;

	var it = $(sel);
    var itHeight = it.height();

	var w = $(window);
    var wHeight = w.height();

    return ( itHeight > wHeight );
}




Called like this

if ( isTooBigToSeeCompletely("#picture4") && isPartiallyVisible(#picture4) ) {
    // Do something useful
}



•       •       •       •       •       •

Summary: # of Words: 224
Author: Philip J. Schlump
Published On: 2013-10-24

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens