Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouseout fires on nested element, I only want it to fire when it leaves the container [duplicate]

Tags:

javascript

Possible Duplicate:
Javascript: Multiple mouseout events triggered

I keep having an issue where I'm looking to see when my mouse exits a container, and the event is fired when I hover over an element contained within the container. I know that jQuery has fixed this problem with the .hover function, but I don't want to use an entire library to solve a single problem. How do I do this in JavaScript?

My question is similar to this question, but I'm not using jQuery.

like image 611
Wex Avatar asked Jan 02 '13 20:01

Wex


1 Answers

Felix had the right answer with his first link. To quote from the article ...

Another show stopper is that when you move the mouse into the layer, and then onto a link, browsers register a mouseout event on the layer! It doesn't make much sense to me (the mouse is still in the layer), but all browsers agree on this one.

So how do we reject any mouseout that does not take place when the mouse actually leaves the layer?

function doSomething(e) {
if (!e) var e = window.event;
var tg = (window.event) ? e.srcElement : e.target;
if (tg.nodeName != 'DIV') return;
var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
while (reltg != tg && reltg.nodeName != 'BODY')
    reltg= reltg.parentNode
if (reltg== tg) return;
// Mouseout took place when mouse actually left layer
// Handle event
}

First get the event target, ie. the element the mouse moved out of. If the target is not the DIV (layer), end the function immediately, since the mouse has certainly not left the layer.

If the target is the layer, we're still not sure if the mouse left the layer or entered a link within the layer. Therefore we're going to check the relatedTarget/toElement of the event, ie. the element the mouse moved to.

We read out this element, and then we're going to move upwards through the DOM tree until we either encounter the target of the event (ie. the DIV), or the body element.

If we encounter the target the mouse moves towards a child element of the layer, so the mouse has not actually left the layer. We stop the function.

When the function has survived all these checks we're certain that the mouse has actually left the layer and we can take appropriate action (usually making the layer invisible).

like image 170
Tims Avatar answered Sep 28 '22 08:09

Tims