Determine which element the mouse pointer is on top of in JavaScript Determine which element the mouse pointer is on top of in JavaScript javascript javascript

Determine which element the mouse pointer is on top of in JavaScript


DEMO

There's a really cool function called document.elementFromPoint which does what it sounds like.

What we need is to find the x and y coords of the mouse and then call it using those values:

var x = event.clientX, y = event.clientY,    elementMouseIsOver = document.elementFromPoint(x, y);

document.elementFromPoint

jQuery event object


In newer browsers, you could do the following:

document.querySelectorAll( ":hover" );

That'll give you a NodeList of items that the mouse is currently over in document order. The last element in the NodeList is the most specific, each preceding one should be a parent, grandparent, and so on.


Although the following may not actually answering the question, since this is the first result of googling (the googler may not asking exactly the same question:), hope it will provide some extra input.

There are actually two different approaches to get a list of all elements the mouse is currently over (for newer browsers, perhaps):

The "structural" approach - Ascending DOM tree

As in dherman's answer, one can call

var elements = document.querySelectorAll(':hover');

However, this assumes that only children will overlay their ancestors, which is usually the case, but not true in general, especially when dealing with SVG where element in different branches of the DOM tree may overlap each other.

The "visual" approach - Based on "visual" overlapping

This method uses document.elementFromPoint(x, y) to find the topmost element, temporarily hide it (since we recover it immediately in the same context, the browser will not actually renders this), then go on to find the second topmost element... Looks a little hacky, but it returns what you expect when there are, e.g., siblings elements in a tree occluding each other. Please find this post for more details,

function allElementsFromPoint(x, y) {    var element, elements = [];    var old_visibility = [];    while (true) {        element = document.elementFromPoint(x, y);        if (!element || element === document.documentElement) {            break;        }        elements.push(element);        old_visibility.push(element.style.visibility);        element.style.visibility = 'hidden'; // Temporarily hide the element (without changing the layout)    }    for (var k = 0; k < elements.length; k++) {        elements[k].style.visibility = old_visibility[k];    }    elements.reverse();    return elements;}

Try both, and check their different returns.