How to easily detect when the mouse leaves the browser window in JavaScript

Detecting when the mouse leaves the browser window helps to track user engagement and display custom messages or popups.

Let’s learn how to do it with JavaScript.

Detect browser window mouse exit

To detect when the mouse leaves the browser window, use the mouseleave event listener:

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> </head> <body> <div id="notifier"></div> <button class="btn-1">Be amazing</button> <script src="index.js" /> </body> </html>
index.js
document.addEventListener('mouseleave', () => { document.querySelector('#notifier').textContent = "Don't leave me!"; });

The mouseleave event fires on an Element when the mouse exits its bounds.

You can also use document.body to listen for when the user exits the window, but the body needs to be as big as the viewport for this to work:

index.js
document.addEventListener('mouseleave', () => { document.querySelector('#notifier').textContent = "Don't leave me!"; });
index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> <style> /* Makes body as big as viewport */ html, body { margin: 0; height: 100%; width: 100%; } </style> </head> <body> <h2>Welcome fellow developer</h2> <div id="notifier"></div> <script src="index.js"></script> </body> </html>

Using document.body over document could be better for compatibility with later Firefox versions.

Detect when user about to exit webpage

This helps to display an exit-intent popup, usually shown when the user is about to close the webpage or go to another.

Since tabs are usually at the top of the browser, we’d detect when the mouse leaves the browser window, but only from the top:

index.js
document.addEventListener('mouseleave', (event) => { if (event.clientY <= 0) { document.querySelector('#notifier').textContent = 'Have a good day!'; } });

clientY will be 0 at the very top of the viewport, so any higher and our if block’s code runs.

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> </head> <body> <h2 id="notifier"></h2> <div> Welcome to Coding Beauty, a site for all things coding. </div> <script src="index.js" /> </body> </html>


Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *