Skip to content

Instantly share code, notes, and snippets.

@gfranko

gfranko/app.js

Created Apr 4, 2013
Embed
What would you like to do?
Method to check if an element is visible. Detects if another element is absolutely positioned on top of it. Should work in IE9+, Firefox 3+, Chrome, and Safari.
isVisible(document.getElementById('at-follow'));
var isVisible = function(elem) {
var w = window, d = document, height, rects, on_top;
if(!elem || (elem && elem.nodeType !== 1) || !elem.getClientRects || !d.elementFromPoint || !d.querySelector || !elem.contains) {
return false;
}
if (elem.offsetWidth === 0 || elem.offsetHeight === 0) {
return false;
}
height = w.innerHeight ? w.innerHeight: d.documentElement.clientHeight;
rects = elem.getClientRects();
on_top = function(r, elem) {
var x = (r.left + r.right)/2,
y = (r.top + r.bottom)/2,
elemFromPoint = d.elementFromPoint(x, y);
return (elemFromPoint === elem || elem.contains(elemFromPoint));
};
for (var i = 0, l = rects.length; i < l; i++) {
var r = rects[i],
in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
if (in_viewport && on_top(r, elem)) {
return true;
}
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.