Skip to content

Instantly share code, notes, and snippets.

@Rooster212
Forked from oslego/elementsFromPoint.js
Last active February 10, 2021 11:51
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Rooster212/4549f9ab0acb2fc72fe3 to your computer and use it in GitHub Desktop.
Save Rooster212/4549f9ab0acb2fc72fe3 to your computer and use it in GitHub Desktop.
Gets all elements below the specified point. Checks to see if browser already has method before using a manual method. Originally found https://groups.google.com/a/chromium.org/forum/#!msg/blink-dev/dTYbg4_S2b8/bEtoAnkP0swJ
// returns a list of all elements under the cursor
//
function elementsFromPoint(x,y) {
var elements = [], previousPointerEvents = [], current, i, d;
if(typeof document.elementsFromPoint === "function")
return document.elementsFromPoint(x,y);
if(typeof document.msElementsFromPoint === "function")
return document.msElementsFromPoint(x,y);
// get all elements via elementFromPoint, and remove them from hit-testing in order
while ((current = document.elementFromPoint(x,y)) && elements.indexOf(current)===-1 && current != null) {
// push the element and its current style
elements.push(current);
previousPointerEvents.push({
value: current.style.getPropertyValue('pointer-events'),
priority: current.style.getPropertyPriority('pointer-events')
});
// add "pointer-events: none", to get to the underlying element
current.style.setProperty('pointer-events', 'none', 'important');
}
// restore the previous pointer-events values
for(i = previousPointerEvents.length; d=previousPointerEvents[--i]; ) {
elements[i].style.setProperty('pointer-events', d.value?d.value:'', d.priority);
}
// return our results
return elements;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment