Reputation: 1563
I would like to use a listener that would trigger a function when the mouse leaves the screen. I'm using the following code:
content = 'blabla';
document.addEventListener("mouseleave", function(){ display_exit(content); });
function display_exit(content)
{ console.log(content); }
When I execute this code on Chrome, it works while on Firefox or Explorer/Edge, nothing happens.
Is there something in my syntax that Chrome is forgiving and not the others?
Thanks
Laurent
Upvotes: 0
Views: 233
Reputation: 9150
"mouseleave" events are fired by Element
objects and do not bubble. A document (document
) is not an Element
and so attaching an event listener to it to listen for "mousemove" events, has no effect, because of the combination of the above two factors.
This has nothing to do with Firefox. It's by design, as proposed by a Web standard body, W3C in this case. If anything, Firefox adheres to the specification, something that cannot be said about Chrome, evidently.
Always consult the authorative reference on the technology you're using before putting it to use and questioning the behavior you yourself assume is wrong: UI Events, W3C Working Draft (that MDN, among others, uses as source)
The solution is to amend your code, making do with the "mouseout" event instead, which does bubble, or be attaching your event listener(s) to elements (e.g. document.documentElement
) instead of a document.
Upvotes: 2
Reputation: 7634
The event is only specified for nodes of type Element
, not for Node
or Documents
:
Type mouseleave
...
Trusted Targets Element
...
You can attach the listener to the documentElement
and it shall work:
document.documentElement.addEventListener("mouseout", ...);
Further, ensure the document (the html
element) has 100% height, otherwise, depending on the content it might not have even entered the document element, thus no leave can be triggered.
See this working fiddle: https://jsfiddle.net/b3wtoayq/
According to the spec I presume it's a bug in Chrome allowing to attach the event listener to the document itself.
Upvotes: 3