Reputation: 73898
I need to detect when an user move out the mouse outside the view-port (example mouse is on browser address bar) even when the mouse button is being held.
As you can see from the code below, I am able to detect it using mouseout
and mouseleave
but when keeping the mouse button hold and moving out of the view-port these events are not fired.
Any idea how to solve this issue?
I target FF and Chrome latest version.
http://jsbin.com/gesehoneri/edit?html,output
document.addEventListener('mouseout', function () {
console.log('mouseout');
})
document.addEventListener('mouseleave', function () {
console.log('mouseleave');
})
Upvotes: 1
Views: 358
Reputation: 255
With this code, if you press the button inside the window, hold it and move the mouse outside the window, it logs the text. Does this help you?
function myFunctioName(e){
if(e.pageY < 0 || e.pageY > window.innerHeight) {
console.log("outside window vertical");
};
if(e.pageX < 0 || e.pageX > window.innerWidth) {
console.log("outside window horizontal");
};
}
window.addEventListener("mousemove", myFunctioName);
window.addEventListener("mousedown", myFunctioName);
Updated for use without JQuery and included both directions.
Upvotes: 0
Reputation: 3926
Try this:
document.addEventListener('mousemove', function(e) {
var top = e.pageY;
var right = document.body.clientWidth - e.pageX;
var bottom = document.body.clientHeight - e.pageY;
var left = e.pageX;
if (top < 10 || right < 10 || bottom < 10 || left < 10) {
console.log('Mouse is out the viewport!');
}
});
body,
html {
height: 100%;
}
Upvotes: 1