1

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');
})
angelcool.net
  • 2,505
  • 1
  • 24
  • 26
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    please check this http://stackoverflow.com/questions/923299/how-can-i-detect-when-the-mouse-leaves-the-window and this also https://api.jquery.com/mouseleave/ hope this will help you – Pardeep Pathania May 03 '16 at 12:34
  • @PardeepPathania thanks for your link, but does not answer my question, I need to detect this event when the mouse button is held. – GibboK May 03 '16 at 12:36
  • How about adding the event listener to the body? Like: `document.body.addEventListener('mouseout',function(){ ..your code here.. }));` – Jeroen May 03 '16 at 12:36
  • You could look into the `onmousedown` event and check to see if the position of the cursor is outside the window. – Ciprianis May 03 '16 at 12:36
  • ok now check this http://stackoverflow.com/questions/30247497/how-to-detect-if-mouse-button-is-held-down-for-a-certain-amount-of-time-after-cl – Pardeep Pathania May 03 '16 at 12:38

2 Answers2

1

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%;
}
NiZa
  • 3,806
  • 1
  • 21
  • 29
0

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.

Ciprianis
  • 255
  • 3
  • 10