Javascript to Detect Mouse Leaving 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!