How to fire a mouse event once to move over children in javascript?

When you enter a DOM element, an event will occur mouseover. When you move the mouse around the current element, an event does not occur, since mouseoverfor input.

However, this rule does not apply to child nodes. If you move the mouse over the child nodes, the event mouseoverwill be fired again and again, although there is no new event, since we are still in the original parent.

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

How can we do it mouseoveronly once to move around the entire parent (source element in addEventListener)? In this example, I want to avoid shooting at an event by moving the mouse to a child.

+5
source share
3 answers

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);

Demo Screenshot

:

+4

, mouseenter, ( mouseover). MDN:

DOM mouseenter , , .

, , , , , .

, . jQuery (. .mouseenter()), . - , :

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);

. , .

+4

in your example, the child element does not fire any event, it is your parent element, on which when you mouse over it it runs your script and displays the result in your time div.

0
source

All Articles