How to check if mouse is inside div with JavaScript?

Sometimes, we want to check if mouse is inside div with JavaScript.

In this article, we’ll look at how to check if mouse is inside div with JavaScript.

How to check if mouse is inside div with JavaScript?

To check if mouse is inside div with JavaScript, we can listen to the mouseenter and mouseout events triggered by the div.

For instance, we write:

<div>
  hello world
</div>

to add a div.

Then we write:

const div = document.querySelector("div")
let isOnDiv = false;
div.onmouseenter = () => {
  isOnDiv = true
  console.log(isOnDiv)
}
div.onmouseout = () => {
  isOnDiv = false
  console.log(isOnDiv)
}

to select the div with querySelector.

Next, we set div.onmouseenter to a function that sets isOnDiv to true.

And we set div.onmouseout to a function that sets isOnDiv to false.

Now when our mouse pointer is in the div, true is logged.

And when our mouse pointer leaves the div, false is logged.