public9nf
public9nf

Reputation: 1399

document mouseover & mouseout firing multiple times - should just fire once

I need to fire two events. One when the cursor enters the document and when he leaves the document. Right now i have a problem that the events also fire when i use the cursor inside the document, you can see this in the console of my fiddle.

How is it possible to just fire the events when i enter and leave the document?

let cursor = document.getElementById('cursor');

function onMousEnter() {
    cursor.classList.add('is-active');
    console.log("Enter!");
}

function onMouseLeave() {
    cursor.classList.remove('is-active');
    console.log("Out!");
}

document.addEventListener('mouseover', onMousEnter);;
document.addEventListener('mouseout', onMouseLeave);

const onMouseMove = (e) => {
    cursor.style.left = e.pageX + 'px';
    cursor.style.top = e.pageY + 'px';  
}

document.addEventListener('mousemove', onMouseMove);

https://jsfiddle.net/k81zbdmj/1/

Upvotes: 0

Views: 34

Answers (1)

Robo Robok
Robo Robok

Reputation: 22673

  1. Use mouseenter instead of mouseover.
  2. Use mouseleave instead of mouseout.

The difference between those is that mouseenter and mouseleave don't bubble. So whenever you move your cursor over or out of a child, those won't trigger the event.

Upvotes: 2

Related Questions