Reputation: 7702
Is there a way to find out if an element is obscured by another element that is not a child of the first one? Because I have a menu that I like to hide when you click anywhere on the page, but not when there is currently a lightbox open that obscures the menu.
Upvotes: 1
Views: 2296
Reputation: 909
If you know which element could be obscuring the "target", you can use the method getBoundingClientRect
to find the edges of the obscurer and the "target". Then it's a problem of finding if two rectangles overlap.
It could seem daunting to calculate that, but to separate the X and Y axes is the Egg of Columbus here.
Two rectangles do NOT overlap if:
1) their X axis range doesn't overlap
a. rect1's bottom is above rect2's top
b. rect1's top is below rect2's bottom
2) their Y axis range doesn't overlap
a. rect1's right edge is to the left of rect2's left edge
b. rect1's left edge is to the right of rect2's right edge
Otherwise--that is, if their X axis overlaps and their Y axis also overlaps--they definitely DO overlap.
function overlaps(el1, el2){
var rect1 = el1.getBoundingClientRect();
var rect2 = el2.getBoundingClientRect();
if (rect1.bottom < rect2.top // 1a
|| rect2.bottom < rect1.top // 1b
|| rect1.right < rect2.left // 2a
|| rect2.right < rect1.left) { // 2b
return false;
}
return true;
}
Upvotes: 0
Reputation: 154818
function isObscured(element) {
// get element at element's position
var elem = document.elementFromPoint(element.offsetLeft, element.offsetTop);
// return whether obscured element has same parent node (will also return false if
// element === elem)
return elem.parentNode !== element.parentNode;
}
http://jsfiddle.net/pimvdb/tKtEV/
Upvotes: 2
Reputation: 12302
You have to evaluate it yourself.
Take into consideration coordinates and size of the frontmost element, then check for "collision" with the elements behind it you need to control.
It's basically a check for overlapping squares.
Upvotes: 0