6

I want to detect when the mouse leaves the viewport on top (to the north so to say). I searched the net and came up with How can I detect when the mouse leaves the window?. Is a good start, but it also detects when the mouse leaves to other directions. How could I only detect the exit on top?

Thanks!

Community
  • 1
  • 1
user4095519
  • 271
  • 1
  • 5
  • 12

2 Answers2

7

In order to detect mouseleave without taking in account the scroll bar and the autcomplete field :

document.addEventListener("mouseleave", function(event){

  if(event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight))
  {
     console.log("I'm out");
  }
});

Then you just have to delete conditions :

event.clientY <= 0  is when the mouse leave from the top
event.clientX <= 0  is when the mouse leave from the left
event.clientX >= window.innerWidth is when the mouse leave from the right
event.clientY >= window.innerHeight is when the mouse leave from the bottom
metodribic
  • 1,561
  • 17
  • 27
Daphoque
  • 4,421
  • 1
  • 20
  • 31
3

Use this plugin: https://github.com/carlsednaoui/ouibounce

It fires an event when the mouse moves out of the top viewport.

enter image description here

bperdue
  • 474
  • 1
  • 6
  • 18