Small script I wrote that does some rudimentary checks to see if an element is visible in the current view (viewport) of the browser.
As far as I can tell it works perfectly cross-browser. It will check the bounding edges of an element, comparing them with window width and height. It will also mark elements with a width or height of zero as not visible.
Note: the script does not take into account overlapping elements, just checks to see if the element is – theoretically – visible, as it – or at least some of it – is visible in the browser window.
Demo
To see a basic example of the script, see this Fiddle.
Code
As a jQuery extension:
$.fn.isVisible = function() {
// Am I visible?
// Height and Width are not explicitly necessary in visibility detection, the bottom, right, top and left are the
// essential checks. If an image is 0x0, it is technically not visible, so it should not be marked as such.
// That is why either width or height have to be > 0.
var rect = this[0].getBoundingClientRect();
return (
(rect.height > 0 || rect.width > 0) &&
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth)
);
};
Usage:
if ($('#myElement').isVisible()) {
//do stuff
};
Regular JavaScript variant:
function isVisible(node) {
// Am I visible?
// Height and Width are not explicitly necessary in visibility detection, the bottom, right, top and left are the
// essential checks. If an image is 0x0, it is technically not visible, so it should not be marked as such.
// That is why either width or height have to be > 0.
var rect = node.getBoundingClientRect();
return (
(rect.height > 0 || rect.width > 0) &&
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth)
);
};
Usage:
if (isVisible(document.getElementById("myElement"))) {
//do stuff
};
View/fork on Github: https://gist.github.com/c-kick/699e67cf3212ade18ce8
No Responses