'mouseenter and mouseleave event listeners on document not working in Firefox
The following code works correctly in Chrome but not in Firefox. In Chrome, when I move my mouse outside and inside the browser, there will be some output in the console, but that is not the case in Firefox. My Firefox version is 85.0.2. Any help would be appreciated.
document.addEventListener("mouseenter", () => {
console.log("mouseenter");
});
document.addEventListener("mouseleave", () => {
console.log("mouseleave");
});
html,
body {
width: 100vw;
height: 100vh;
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
</body>
</html>
Solution 1:[1]
Try to give dimensions to the page and use body instead
document.querySelector("body").addEventListener("mouseenter", () => {
console.log("mouseenter");
});
document.querySelector("body").addEventListener("mouseleave", () => {
console.log("mouseleave");
});
html, body { width: 100vw; height:100vh; background-color:red; }
A test of the event listener
const addEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(name, handler) {
addEventListener.call(this, name, function(event) {
window.event = event;
handler(event);
})
};
function showEvent(e) {
// just demonstrating that window.event is set
console.log(e.type);
}
document.addEventListener('mouseenter', showEvent);
document.addEventListener('mouseleave', showEvent);
document.addEventListener('mouseover', showEvent);
document.addEventListener('mouseout', showEvent);
html,
body {
width: 100vw;
height: 100vh;
background-color: red;
}
https://stackoverflow.com/questions/47786133/workaround-for-firefoxs-lack-of-window-event
Solution 2:[2]
It may be because the page isn't fully loaded:
window.onload = (event) => {
const element = document.getElementsByTagName('body')[0];
element.addEventListener("mouseenter", () => {
console.log("mouseenter");
});
element.addEventListener("mouseleave", () => {
console.log("mouseleave");
});
};
Live demo: https://www.w3schools.com/code/tryit.asp?filename=GNQZGHTD6CC9
worked on Firefox.
Solution 3:[3]
Try document.documentElement.addEventListener('mouseleave', () => {})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Pallav Jha |
