JavaScript event handler

108 views Asked by At

I am trying to fix a bug with the mouseenter and mouseleave handler.

listener.addEventListener('mouseenter', function(){
    element.style.visibility = "visible";
}, true);

listener.addEventListener('mouseleave', function(){
    element.style.visibility = "hidden";
}, true);

The events work as expected except for when i am moving the mouse over the element it flashes the mouse leave event.

Any fixes for this?

Plain javascript solutions only, please (no 3rd party libraries).

2

There are 2 answers

4
6502 On

The pointer in Javascript is only "hovering" the topmost (visible) element.

This means that if you've say a background div and when "entering" it you display another div on top of it the cursor will exit the background to enter the new div.

May be you can just set opacity to 0 instead of hiding the div and leave it always "visible" (also placing the event handler in the appearing div, not in the background one).

2
Mehran Hatami On

There is property named relatedTarget in the mouse event, which would help you fix it. you should check if it is not in the area like:

listener.addEventListener('mouseleave', function(event){
    if(!event.relatedTarget ||
       (event.relatedTarget != listener && event.relatedTarget.parentNode != listener))
        element.style.visibility = "visible";
    else
        alert("I am still in listener area but mouseleave got triggered :)))");
}, true);

The point here is I have checked only for the first parent level, but you better create a function to check it for all the DOM tree in the listener node. I mean it could be one of the nested childNodes in the listener node.

I know it seems kind of weird, but it is the way it is, sometimes when it enters to a child nodes area mouseleave gets triggered.