Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Know all the elements under your mouse pointer (multiple z-axis layers)

Tags:

javascript

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?

like image 568
Lurk21 Avatar asked Dec 01 '22 17:12

Lurk21


1 Answers

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;
}

Update:

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/

like image 101
Mircea Avatar answered Dec 10 '22 12:12

Mircea