How to fire mouse event once for moving over child elements in Javascript?

When entering a DOM element, mouseover event will happen. Upon moving the mouse around the current element, no event happens, as mouseover is for entering.

However, this rule is not obeyed for child nodes. If moving the mouse over child nodes, the mouseover event will be triggered again and again, though no new event, as we are still in the original parent.

See this example. If we move the mouse over the parent (actually on its textNode), nothing new happens, but if we go to the child element (still on the parent), it will trigger the mouseover event again and again. In fact it will fire the mouse event every time mouse enters an elements (even inside the original parent element).

How we can make the mouseover only once for moving all over the parent (the original element in the addEventListener)? In the given example, I mean to avoid firing the event upong moving the mouse on the child element.



This works for me in chrome and ff

document.getElementById("parent").addEventListener('mouseover', function(event) {
    var e = event.fromElement || event.relatedTarget;
    if (e.parentNode == this || e == this) {
    document.getElementById("time").innerHTML = new Date();
}, true);

Fiddle Demo

Reference: Mouse Events


What you really need is the mouseenter event, which does not bubble (unlike mouseover). From MDN:

The synchronous mouseenter DOM event is dispatched when a mouse or another pointing device enters the physical space given to the element or one of its descendants.

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.

Unfortunately, it's not widely supported. One solution is to use jQuery (see .mouseenter()), which polyfills that event in all the browsers it supports. Another option is to check the element that triggered the event:

document.getElementById("parent").addEventListener('mouseover', function(e) {
    if ( === "parent") { //Only execute following on parent mouseover
        document.getElementById("time").innerHTML = new Date;
}, false);

Or see here for what looks at first glance to be a pretty good shim.


in your example child element is not firing any event it is your parent element on which when you mouseover it runs your script and display result in your "time" div.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.