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

Last updated on November 02, 2023
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:

<!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>
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:

document.addEventListener('mouseleave', () => {
  document.querySelector('#notifier').textContent =
    "Don't leave me!";
});
<!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:

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.

<!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>
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also