So there's this really cool fiddle which allows you to fetch the element under your pointer:
http://jsfiddle.net/MPTTp/
$(window).click(function(e) {
var x = e.clientX, y = e.clientY,
elementMouseIsOver = document.elementFromPoint(x, y);
alert(elementMouseIsOver);
})
I have multiple z-axis layers, and I want to know ALL the elements under my pointer.
Any advice?
Just look under each element until you reach the html tag. You can hide/show elements or use pointerEvents for this:
http://jsfiddle.net/Gwy2u/
$(window).click(function(e) {
var x = e.clientX,
y = e.clientY,
stack = [],
elementMouseIsOver = document.elementFromPoint(x, y);
stack.push(elementMouseIsOver);
while (elementMouseIsOver.tagName !== 'HTML'){
elementMouseIsOver.style.pointerEvents = 'none';
elementMouseIsOver = document.elementFromPoint(x, y);
stack.push(elementMouseIsOver);
}
/* Now clean it up */
var i = 0,
il = stack.length;
for (; i < il; i += 1) {
stack[i].style.pointerEvents = '';
}
console.log(stack);
});
along with this css style:
.pointerEventsNone {
pointer-events: none;
}
Using classList to add/remove a pointer-events propriety is more elegant: as demonstrated in this fiddle and below:
function elementsAtLocation (x,y){
var stack= [], el;
do {
el = document.elementFromPoint(x, y);
stack.push(el);
el.classList.add('pointerEventsNone');
}while(el.tagName !== 'HTML');
// clean up
for(var i = 0; i < stack.length; i += 1)
stack[i].classList.remove('pointerEventsNone');
return stack;
}
Old browsers: Using display:none for older browser, however this will trigger repaint/reflow: http://jsfiddle.net/Gwy2u/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With