Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 upon moving the mouse on the child element.

like image 486
Googlebot Avatar asked Jun 26 '12 07:06

Googlebot


2 Answers

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 (e.target.id === "parent") { //Only execute following on parent mouseover
        document.getElementById("time").innerHTML = new Date;
        this.childNodes[1].style.display="block";
    }
}, false);

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

like image 75
James Allardice Avatar answered Nov 01 '22 10:11

James Allardice


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) {
        return;
    }
    document.getElementById("time").innerHTML = new Date();
}, true);

Fiddle Demo

Reference: Mouse Events

like image 23
Jashwant Avatar answered Nov 01 '22 09:11

Jashwant