onMouseEnter event is not working. When mouse pointer is scrolled into the div body

Viewed 34

Try this is JavaScript, create div and add a onmouseenter event on that div, when you move the mouse cursor on to the div, this event will be called as expected. but this event is only called when you move the cursor onto the div body not when you scroll into the div body, scroll down into the page and place the mouse cursor where the div is suppose to be, Now without moving the cursor scroll back up and the cursor will eventually end up on the div body but in this case onmouseenter event is not called.

  document.querySelector('div').onmouseenter = () => {
    console.log('hereInDivBody')
  }

How can I fix this?

1 Answers

First the event is called mouseenter or mouseover but not onmouseenter (which exist as an attribute). In JS you need to add an `eventListener) to listen for that event in the first place:

document.querySelector('div').addEventListener('mouseenter', function() {
  console.log('hereInDivBody');
})
div {
  height: 50vh;
  border: 2px dashed red;
}
<div></div>

Related