Detect when the mouse leaves the top of the viewport?
Asked Answered
M

2

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!

Machute answered 30/9, 2014 at 14:55 Comment(4)
Track the position and put a guard on the last known position after detecting that the mouse left the window.Callie
What exactly do you mean? Would you explain a bit more pls?Machute
Figured it out myself, thanks!Machute
You'll need to tell us which language and platform you're using if you want a useful answer. Please edit the tags of the question with that information. Thanks.Switcheroo
S
9

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
Scoles answered 16/1, 2018 at 12:55 Comment(0)
H
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

Horrorstruck answered 31/8, 2015 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.