2

I've assigned an onmouseover event to my html body. However, I only want it to fire once, when the mouse enters the body.

Instead, it's firing repeatedly, whenever I move my mouse in the body, even if the mouse never left the body.

Is there a way to prevent these misfires?

Thanks

johny why
  • 2,047
  • 7
  • 27
  • 52
  • Learn all the events you have at your disposition and their differences. https://developer.mozilla.org/en/docs/Web/API/Event -- https://developer.mozilla.org/en-US/docs/Web/Events – Roko C. Buljan Aug 27 '15 at 01:14
  • @mwilson, what do you mean "both" events? i only want one event. – johny why Aug 27 '15 at 01:15

1 Answers1

5

You need to use the event mouseenter not mouseover which will be triggered when you move from element to element.

The mouseenter event is fired when a pointing device (usually a mouse) is moved over the element that has the listener attached.

Similar to mouseover, it differs in that it doesn't bubble and that it isn't sent when the pointer is moved from one of its descendants' physical space to its own physical space.

document.body.addEventListener('mouseenter', function() {
  snippet.log('mouse entered')
});
document.body.addEventListener('mouseover', function() {
  snippet.log('mouse over')
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<div>Soem content <span>within span</span> <button>Button</button></div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531