I need to check with jQuery if a DIV element is not falling off-screen. The elements are visible and displayed according CSS attributes, but they could be intentionally placed off-screen by:
position: absolute; left: -1000px; top: -1000px;
I could not use the jQuery :visible
selector as the element has a non-zero height and width.
I am not doing anything fancy. This absolute position placement is the way my Ajax framework implements the hide/show of some widgets.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
The top side of the element must be below the top side of the window OR the bottom side of the element must be above the bottom side of the window, AND. The left side of the element must be to the right of the left side of the window OR the right side of the element must be to the left of the right side of the window.
To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0. The Javascript code could be written as : window.
You can use .is(':visible') selects all elements that are visible.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With