user673763
user673763

Reputation: 1

Onmousemove, onmouseover and onmouseenter. Why doesn't it work?

This code works for onmousemove and onmouseover but it doesn't work for onmouseenter.

If I move the pointer on the second div it remains "second". Why?

I don't understand.

var movecounter = 0;
var entercounter = 0;
var overcounter = 0;
onmousemove = myFunction1;
onmouseenter = myFunction2;
onmouseover = myFunction3;

function myFunction1() {
  movecounter++;
  document.getElementById("first").innerHTML = "MouseMove: " + movecounter;
}

function myFunction2() {
  entercounter++;
  document.getElementById("second").innerHTML = "MouseEnter: " + entercounter;
}

function myFunction3() {
  overcounter++;
  document.getElementById("third").innerHTML = "MouseOver: " + overcounter;
}
<!DOCTYPE html>
<html>

<body>

  <div id="first">first</div>

  <br>

  <div id="second">second</div>

  <br>

  <div id="third">third</div>

</body>

</html>

Upvotes: 0

Views: 935

Answers (1)

Bellian
Bellian

Reputation: 2140

Hi and welcome to StackOverflow.

The onmouseenter you are using is the event of the global Window itself and might not work as intended. See https://developer.mozilla.org/en-US/docs/Web/API/Window#Event_handlers for all available event handlers of the Window. Not all event handler support all the possible events defined by GlobalEventHandlers.

The easyest fix is to bind the event to a element you want listen to (for example the document or the body element).

In general:

  • mousemove: Will trigger as soon the pointer moves inside the element the event is bound to.

  • mouseover: Will be triggered as soon as you move over an element the event is bound to or any other child element. for every "change" a new event will be emitted.

  • mouseenter: Will be triggered as soon as the pointer enters the element the event is bound to. it will only trigger again if the pointer beforehand leaves the element.

var movecounter = 0;
var entercounter = 0;
var overcounter = 0;
document.body.onmousemove = myFunction1;
document.body.onmouseenter = myFunction2;
document.body.onmouseover = myFunction3;

function myFunction1(){
  movecounter++;
  document.getElementById("first").innerHTML = "MouseMove: " + movecounter;
}

function myFunction2(){
  entercounter++;
  document.getElementById("second").innerHTML = "MouseEnter: " + entercounter;
}

function myFunction3(){
  overcounter++;
  document.getElementById("third").innerHTML = "MouseOver: " + overcounter;
}
<html>
  <body>
    <div id="first">first</div>

    <br>

    <div id="second">second</div>

    <br>

    <div id="third">third</div>
  </body>
</html>

Upvotes: 1

Related Questions