Javascript to Detect Mouse Leaving Browser Window

  • follow us in feedly
Published March 26, 2014 by Brad Knutson
Javascript to Detect Mouse Leaving the Browser Window

I’ve recently become a bit obsessed with my high sites high bounce rates. I’m talking really high bounce rates, in the 80-85% range.

The optimist in me interprets this as the vast majority of my visitors are looking for one specific solution, they find it on my site, and that’s the extent of our relationship. If 80% of my sites traffic is finding what they’re looking for in one page, then that’s a good thing, right?

The pessimist in me says that most of my traffic isn’t finding the answer they are looking for – so I must do a better job.

It could be a combination of the two, it’s hard to say.

Which is why I decided that I wanted to do some tests. I want my website to know that my visitor is about to leave the page, and attempt to grab their attention. After some thought, I determined the best way to measure “intent” to leave a website is to capture a visitor when they move the mouse to the browsers back or close buttons. Essentially, whenever the cursor leaves the browser window, I’m going to assume you’re attempting to leave my site. This isn’t foolproof of course, and there are plenty of other legitimate reasons to move the cursor outside of the browser window (for example – by mistake, to open an email notification, to go back and forth between two monitors, to open a code inspector, etc.). Still, I think this is a good place to start.

So, I started capturing visitors to my site who are attempting to leave. If this is your first time to my site (and you’re reading this within 10 seconds of page load), try mousing out of the browser window. You’ll see my friendly popup.

But how do we capture the cursor leaving the browser?

jQuery Solution…Sort of

Ah, my good old friend jQuery. No doubt you have an easy solution, no?

Huzzah! Look how easy that is!

Tests code snippet out in Internet Explorer

For crying out loud…

Yea, unfortunately this solution does not work in Internet Explorer 10 or 11. If you want it to work in those Internet Explorer versions, you’ll need this:

OK, so a minor difference. No big deal. But now we have to test the user agent string to determine what browser (and what version) the end user has. This doesn’t sound like an ideal solution.

So jQuery can’t come through for me this time. I bet there is a vanilla javascript solution that is cross-browser compatible though.

Vanilla Javascript Solution

First a little function from Peter-Paul Koch; cross browser event handler:

Next, we’ll use this method to attach an event handler to the window (actually the DOM) mouseout event:

That should do it! I’ve tested in all the major desktop browsers and it works like a charm!

Think you have a better solution? Let me know in the comments below!

The following two tabs change content below.
Founder at Inbounderish
Brad Knutson is a Web Developer in the Twin Cities area of Minnesota. He has experience working with WordPress and Drupal, and also has an interest in SEO and Inbound Marketing.

Keep Up-to-Date

Subscribe

Topics

See a complete list of topics discussed in blog posts here.

Check These Out

Get 2 Weeks Free! Sign Up Today! Premium Managed WordPress Hosting Genesis Framework for WordPress SEO is complex. Tools should be simple. Thesis Theme for WordPress:  Options Galore and a Helpful Support Community

10 thoughts on “Javascript to Detect Mouse Leaving Browser Window

  1. Jay

    Can you make this work when using alt+tab to switch away from the browser, such as to an editor where I copy and paste your code?

    Reply
    1. Brad Knutson Post author

      Hey Jay – I’m not aware of any way to trigger off alt+tab (or any way to disable it) – but you could try onfocus or onblur depending on what you are trying to accomplish.

    2. Graham


      $(window).on("keydown", function(e) {
      if(e.keyCode == 18) {
      $(window).on("keydown", function(x) {
      if (x.keyCode == 9) {
      // code to be executed here
      }
      });
      }
      });

  2. Dave

    Thank you very, very much for this.

    As some advice, I would recommend changing the “Go Away!” button. This is confusing and does not easily communicate the action of staying on/viewing the current page. Seems more like, leaving the site.
    Also, if someone is bouncing from your page within 10 seconds of landing, it seems that they would not be interested in reading your blog, or hiring you, as they have not yet received the value you were hoping to deliver. It seems like this would be instead, a great place to offer free/other content. A lead magnet, or popular topic, etc.

    Reply
    1. Anon

      Some additional information. This appears to be a bug in the latest versions of Chrome which use Blink. On entering the browser window, Chrome seems to be firing the following events all very close together: mouse in, mouse out, then mouse in again.

  3. Neville Franks

    I’ve been trying all sorts of hacks to detect when the mouse moves out of an iframe or when the left button is released outside of an iframe and nothing worked until I found your post. A big thanks from me and Clibu.

    Reply
  4. Dan King

    Hey Brad! Thanks so much for this….really going to come in useful. I do have a question though – any way to get it to fire only once using jQuery? I’ve found additional JS code to leave a cookie and have pieced that code and your code together so that users are not bothered by my event (a popover) when they refresh the page.

    But if they mouse out before they refresh the page, the event is fired again. How do I prevent this?

    Thanks so much!
    Dan K.

    Reply
  5. Ivan

    Both solutions work, but it makes bad experience to users, and it doesn’t support mobile device ( because there is no mouse event in mobile )
    Best solution is to use window.onbeforeunload

    Reply

Share Your Thoughts

Your email address will not be shown.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">