简体   繁体   中英

Javascript = AddEventlistener only working on Chrome

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

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.

"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 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)

Your solution is to amend your code, considering whether you can make do with "mouseout" event instead, which does bubble , or be attaching your event listener(s) to the elements you want to listen for "mouseleave" events for, including the document.documentElement element, if applicable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM