Bort
Bort

Reputation: 551

How can it be detected when the mouse cursor leaves the webpage if the cursor doesn't touch the edge?

I'm looking for a non-JQuery solution for a seemingly simple task: Detecting when the mouse has left the page. BUT, standard methods using:

document.onmouseleave
//or
document.onmouseout

will only work if the mouse leaves the page via the edge.

That means it will fail if the mouse leaves by crossing over into another program that has a higher focus (eg: Notepad.exe).
It will also fail if the browser is minimized (eg: Win+D), or if Alt+Tab is used. There are probably other ways it will fail.

What other methods are there that have a better success at detecting the mouse leaving? Perhaps even through polling?
This must work in Chrome+Windows, but ideally any modern browser.

Update:
dman2306 has linked to some methods for detecting when the browser is minimized, including:

document.addEventListener("visibilitychange", function() {
  doThings();
}, false);

I just verified that works in the latest version of Chrome on Windows 8.1.

That that just leaves the issues of the cursor exiting via another Window's edge, or via Alt+Tab.

Upvotes: 1

Views: 727

Answers (2)

Alex Kudryashev
Alex Kudryashev

Reputation: 9470

There is an event onblur which does what you want.

    window.onblur = function () {
        console.log('blur');
    }

Upvotes: 1

Guy haimovitz
Guy haimovitz

Reputation: 1625

You can add to you solution another handler for onfocusout event, that will detect if another program got focus or if the window was minimized.

Upvotes: 0

Related Questions