Mouseleave triggered by click
I also ran into this bug. In my case, I added label wrapped checkboxes into a list, and wrapped the list in a div. I also used some list items that were <hr>
tags. If you click around the checkboxes and labels quickly you will occasionally trigger a mouseleave
event on the wrapping div. This shouldn't occur as all clicked elements are children of the div.wrapper
.
...
wrapper.addEventListener(
'mouseleave',
(e) => {
logger('mouseleave fired');
console.log('mouseleave fired', e);
},
false
);
...
jsfiddle demo
Here's a gif of the reproduction. Click within the clue area (granted with some intensity and movement), click events from the label and input boxes are firing and then you see two mouseleave events fire in error, and then a third when the mouse truly leaves the blue area.
This seems to be a bug (I could reproduce it in Chrome with clicks that have the mouse down and mouse up happening rapidly after each other).
I would suggest to work around this issue by checking whether the mouse is still over the element at the moment the event is fired:
tooltip.onmouseleave = (e) => {
if (tooltip === document.elementFromPoint(e.clientX, e.clientY)) {
console.log('false positive');
return;
}
console.log('tooltip mouse OUT')
}
The downside is that when the browser window loses focus, that is also considered a false positive. If that is an issue for you, then check this answer.
I had previously looked at the answers and comments here, but recently found a way to check if the mouseleave
event was triggered erroneously
I added a check in my mouseleave
handler:
private handleMouseLeave(event: MouseEvent) {
if(event.relatedTarget || event.toElement){
// do whatever
}
// otherwise ignore
}
From my testing on Chrome v64, both of these values will be null
whenever fast clicking causes the mouseleave
event to be triggered. The relatedTarget
is for older browser compatibility
Note: both of these values will also be null
if the mouse leaves the target
element and enteres the Browser (e.g. the tabs, menus etc), or leaves the browser window. For my purposes that was not a problem, as it is a sliding menu I am working with, and leaving the Browser window should not close the menu in my particular case.
Note: latest Firefox release (Feb 2018) seems to trigger mouseleave
on every click of my menu! Will have to look into it