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:

document.addEventListener('mousemove', e => {
  console.clear()
  console.log( document.elementFromPoint(e.clientX, e.clientY) )
}, {passive: true})
[class^='level']{
  width: 100px;
  height: 100px;
  padding: 15px;
  background: #00000033;
}
<div class="level-1">
  <div class="level-2">
    <div class="level-3">
      Hover
    </div>
  </div>
</div>

document.elementFromPoint

jQuery event object

Leave a Comment