Categories
JavaScript Answers

How to check if mouse is inside div with JavaScript?

Spread the love

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.

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 *