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

Tom Lehman picture Tom Lehman · Jan 11, 2012 · Viewed 105.4k times · Source

I want a function that tells me which element the mouse cursor is over.

So, for example, if the user's mouse is over this textarea (with id wmd-input), calling window.which_element_is_the_mouse_on() will be functionally equivalent to $("#wmd-input").

Answer

qwertymk picture qwertymk · Jan 11, 2012

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