Mouseover and mouseout problem

I discovered recently that it causes headache when using mouseover and mouseout events together on one HTML element. This will not have any problem if that element does not have any child element, otherwise,  the problem starts. My problem occurred when I tried to use special effects when mouseover and mouseout of an element which has one child element. The effects became to be very flickering. After a while of searching on the internet as usual, I found a post which explains the problem very well. It is because:

First mouseover event is fired when mouse over the REAL observed element, and then when the mouse moves into the child element, it thinks that your mouse has moved out from the REAL observed element so that its mouseout event is fired, but soon it realizes that the mouse is still within the area of its parent and then fires again its mouseover event….

I guess in most of the cases, this is not a proper behavor that one wants to be. Below I have pasted some code that I found which solves my problem very well:

function isMouseLeaveOrEnter(e, handler) {
    if (e.type != 'mouseout' && e.type != 'mouseover') return false;
        var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ?
        e.toElement : e.fromElement;

    while (reltg && reltg != handler)
        reltg = reltg.parentNode;

    return (reltg != handler);
}

In the code above, e is the element which the current event belongs to and handler is the REAL observed element. The problem is solved by calling this function before executing your real event handler’s code.

I hope this could help anyone else who has this similar annoying problems.

Tagged with:

Recent Entries

2 Comments

  1. luppin says:

    OMG,
    I looked for this solution every where!!
    I posted a question about it on every javascript forum and didn’t get any decent and so efficient answer!!

    I usually don’t leave comments on blogs, but this time I simply must.
    thank you very much!
    You blog is now in my favorite list :)

  2. TrentonC says:

    How would I go about implementing this, calling it? I have a div that contains other divs and elements, I only want the function I’m calling to execute when I mouse over, like you’re addressing here.

    I am working with the prototype framework as well…

Leave a Reply