user4095519
user4095519

Reputation: 281

Detect when the mouse leaves the top of the viewport?

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!

Upvotes: 6

Views: 4257

Answers (2)

Daphoque
Daphoque

Reputation: 4678

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

Upvotes: 9

bperdue
bperdue

Reputation: 484

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

Upvotes: 3

Related Questions