I want to fire an action to dataLayer if the mouse moves off the page. I'm assuming adding an event listener would work and passing in 'mouseout' but needed some help setting it up as I am new to javascript. Thank you !
Asked
Active
Viewed 48 times
-1
-
please confirm me. Is page document.body? – Jerry Nov 16 '22 at 15:11
-
1Can you please elaborate your use-case here ? There are quite a few ways to achieve the above. Also what does your code look like ? Please include the code as well If you have any. Thanks – Aravind Reddy Nov 16 '22 at 15:12
-
Does this answer your question? [Is there a way to detect if a browser window is not currently active?](https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) – Elias Soares Nov 16 '22 at 17:13
1 Answers
0
something like:
document.addEventListener("mouseleave", (event) => {
if (event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight)) {
/* do what you have to do here */
}
});
Following Luke McCrea, I made the test with the following:
document.addEventListener("mouseleave", (event) => {
/* do what you have to do here */
}
});
Seems to work same. It was a quick on a blank HTML page, with nothing else loaded. But no real reason it's not working on real big project.

pier farrugia
- 1,520
- 2
- 2
- 9
-
-
@luke if out do something, that's the only need of this statement – pier farrugia Nov 16 '22 at 15:33
-
@pierfarrugia can you explain clientY, clientX, innerWidth and innerHeight? is this to specify that it's going off the actual page? – SuperSako22 Nov 16 '22 at 15:50
-
1@pierfarrugia Is there a need for it though? doesn't the event listener work fine without it? – Tim Nov 16 '22 at 16:03
-
@luke seems you are right, I just made the test. quick test, it's working same – pier farrugia Nov 16 '22 at 17:04
-
@SuperSako22 for event.client see here https://www.w3schools.com/jsref/event_clientx.asp, for inner check here https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth – pier farrugia Nov 16 '22 at 17:06