Get element from point when you have overlapping elements?
Not sure for what reason the initial question was asked, but if you need to detect an element under currently draggable with touch or mouse element, you can set pointer-events: none;
on the draggable element. When you do this, document.elementFromPoint()
will ignore currently draggable element and return the one underneath it.
If you want to find all the DOM elements that overlap over a point, you can simply use document.elementsFromPoint(), which returns an array of all elements found in said point (apparently, ordered from top to bottom relative to the viewport, i.e.: if there's an overlay, it will show up first in the array)
As I think you already know, document.elementFromPoint(x, y);
only returns the top-most element that overlaps that point.
If what you're trying to do is find all elements that overlap with a given point, even elements behind other elements, then I'm not aware of any DOM function that will do that for you. You may have to write your own.
A somewhat hackish version would be to call elementFromPoint(x,y)
, remember that DOM item, then hide that item with display: none
, then call elementFromPoint(x,y)
again until all you get is the body, then restore the items you hid.
A less hackish version would be to cycle though all objects in the page and compare their offset/height/width in the page to your point.
Here's one way to do it:
function getAllElementsFromPoint(x, y) {
var elements = [];
var display = [];
var item = document.elementFromPoint(x, y);
while (item && item !== document.body && item !== window && item !== document && item !== document.documentElement) {
elements.push(item);
display.push(item.style.display);
item.style.display = "none";
item = document.elementFromPoint(x, y);
}
// restore display property
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = display[i];
}
return elements;
}
Working demo: http://jsfiddle.net/jfriend00/N9pu9/