In today’s tutorial we’ll be taking a look at how to triggering a function on mouse leaving the browser window. What can this be used for? Well, for example you can use it to trigger a popup when your visitors want to leave or other useful stuffs and things.

For example, the popuplar OptinMoster WordPress Plugin uses the same thing to trigger the opt-in when the visitor is about to leave.

Triggering a Function on Mouse Leaving the Browser

This can be achieved very easily. First off we need jquery in our document. To do this, simply add the following line in the <head></head> of your document.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

After this, we need to create a new javascript function to track the cursor. This looks like the following:

function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}

And after this, the only thing we need to do is to do something when the mouse leaves the browser. For the sake of this tutorial, we’ll just alter the user that he left the browser window.

addEvent(document, 'mouseout', function(evt) {
    if (evt.toElement == null && evt.relatedTarget == null) {
        alert('Left the Canves');
    }
});

To change what happens when the user leave the window, simple change the alert('Left the Canves');line.