How to check if an element is off-screen
Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?
Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):
jQuery.expr.filters.offscreen = function(el) {
var rect = el.getBoundingClientRect();
return (
(rect.x + rect.width) < 0
|| (rect.y + rect.height) < 0
|| (rect.x > window.innerWidth || rect.y > window.innerHeight)
);
};
You could then use that in several ways:
// returns all elements that are offscreen
$(':offscreen');
// boolean returned if element is offscreen
$('div').is(':offscreen');
There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.
$('#element').visible();
You can also check for partial visibility:
$('#element').visible( true);
One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.