Categories
JavaScript Answers

How to Determine Which Element the Mouse Pointer is on Top of in JavaScript?

Spread the love

We can use the document.elementsFromPoint method to get elements that our mouse is hovering over.

For instance, if we have the following HTML:

<div id="outer">  
  <div id="inner1">foo</div>  
  <div id="inner2">bar</div>  
  <div id="inner3">baz</div>  
  <div id="inner4">qux</div>  
</div>

Then we can write:

window.addEventListener('mouseover', (e) => {  
  const {  
    clientX: x,  
    clientY: y  
  } = e  
  const elementMouseIsOver = document.elementFromPoint(x, y);  
  console.log(elementMouseIsOver)  
})

to get which element our mouse is hovering over.

We call window.addEventListener with 'mouseover' to listen to the mouseover event on the whole browser window.

Then in the event handler callback, we get the clientX and clientY properties, which are x and y coordinates of the mouse on the browser window.

Next, we pass both into elementFromPoint to get the element at the x and y coordinates.

When we move our mouse over the elements, we should see the element at those coordinates logged.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *