Web design tutorials and tools since 2014Privacy
Search 151 articles

Coding

Create an Exit Intent Popup Window

In this tutorial we’re going to create an exit intent popup window. First, we’ll talk about what exit intent is, then I’ll walk you through the steps of creating the popup window, then we’ll create the exit intent script.

Two laptops, one with a heat map of cursor movement and one showing a popup window.

We’re going to use the modal window style from a previous tutorial: pure CSS modal window

What is Exit Intent?

Exit intent is a technology that tracks when the visitor is about to leave the website and then it does something. For example a subscription box pops up or something similar. Many sites use this technology to increase email subscribers and get back visitors who are about to leave.

The basic idea behind this is, that there’s a JavaScript that tracks the size of the browser window, and if the cursor leaves that box, it triggers another function.

Here’s a tutorial on how this works: Trigger a Function on Mouse Leaving the Browser with jQuery

Creating the Modal Window

A page with a white lightbox titled Your title and content shown at the top after the popup slides down.
The popup as it looks once the script reveals it.

First, we need to create the modal window itself. I won’t go into details about this here, you can check the tutorial above for a more detailed explanation on this.

The HTML

<div class="lightbox" id="text">
    <div class="box">
        <a class="close" href="#">X</a>
        <!-- your title -->
        <div class="content">
        <!-- your content -->
        </div>
    </div>
</div>

The CSS

.lightbox {
    /** Hide the lightbox */
    display: none;

    /** Apply basic lightbox styling */
    position: fixed;
    z-index: 9999;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    color:#333333;
    }

.lightbox:after {
    content: '';
    display: table;
    clear: both;
}

.lightbox .box {
    width: -webkit-min-content;
    width: -moz-min-content;
    width: min-content;
    min-width:500px;
    margin: 2% auto;
    padding:20px;
    background-color:#FFF;
    box-shadow: 0px 1px 26px -3px #777777;
    }

    .lightbox .title {
        margin:0;
        padding:0 0 10px 0px;
        border-bottom:1px #ccc solid;
        font-size:22px;
        }

    .lightbox .content {
        display:block;
        padding:10px 0 0 0px;
        font-size:18px;
        line-height:22px;
        }

    .lightbox .close {
        float:right;
        display:block;
        text-decoration:none;
        font-family:Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size:22px;
        color:#858585;
        }

.lightbox.open {
    /** Show lightbox when mouse leaves the browser window */
    display: block;
    outline: none;
}

Triggering the Popup with Exit-Intent

For us to be able to use this method, we’ll need to include jQuery into our project.

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

After we have that, we can move on to the script. I’ll explain below.

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

// Exit intent trigger
addEvent(document, 'mouseout', function(evt) {

    if (evt.toElement == null && evt.relatedTarget == null ) {
        $('.lightbox').slideDown();
    };

});

// Closing the Popup Box
$('a.close').click(function(){
    $('.lightbox').slideUp();
});

First, we track whether the mouse is still in the browser window, then we trigger it with an if statement. If it’s triggered, we slide down our popup window. After that, we create a short script, that if we click the close button the popup slides back up.

A cursor leaving the browser window through the top, next to the mouseout code that slides the popup down.
The mouseout check that triggers the popup.

And that’s it, we have our exit-intent triggered popup window.

The check works because when the mouse leaves the page, the mouseout event has no element it’s moving to, so relatedTarget is null. toElement is an old Internet Explorer property, and you can leave it out today.

Show the popup only once

As written, the popup appears every time the cursor leaves the window, which gets annoying fast. Remember that the visitor has seen it, and only trigger it when the cursor leaves through the top of the page, toward the tabs and address bar, rather than off the side:

document.addEventListener('mouseout', (event) => {
    const leftTheTop = !event.relatedTarget && event.clientY <= 0;
    if (!leftTheTop) return;
    try {
        if (localStorage.getItem('exitPopupSeen')) return;
        localStorage.setItem('exitPopupSeen', Date.now());
    } catch (e) { /* storage blocked: show it anyway */ }
    $('.lightbox').slideDown();
});

localStorage keeps the flag until the visitor clears their browser data. Use sessionStorage instead if it should show once per visit. To show it again after a week, compare the stored time with Date.now().

It also helps to wait a few seconds before arming the script. Someone who leaves within two seconds of arriving probably clicked the wrong result, and a popup won’t change their mind.

A more accessible popup with dialog

The <dialog> element is now supported in every current browser, and it handles the hard parts of a modal for you: it traps keyboard focus inside the popup, closes on the Escape key and hides the rest of the page from screen readers while it’s open.

<dialog id="exit-popup" aria-labelledby="exit-title">
    <h2 id="exit-title">Before you go</h2>
    <p>Get one web design tutorial a week in your inbox.</p>
    <form method="dialog">
        <button>No thanks</button>
    </form>
</dialog>
const popup = document.getElementById('exit-popup');
document.addEventListener('mouseout', (event) => {
    if (!event.relatedTarget && event.clientY <= 0 && !popup.open) {
        popup.showModal();
    }
});
#exit-popup::backdrop {
    background: rgb(0 0 0 / 50%);
}

A button inside <form method="dialog"> closes the dialog with no extra code. Combine this with the localStorage check above so it only shows once.

What about phones?

There’s no mouse on a touch screen, so mouseout never fires the way it does on a desktop and the popup simply won’t appear. That’s usually fine. Common mobile substitutes, like showing the popup when the visitor scrolls back up quickly or presses Back, tend to feel like a trap. Google’s guidance on intrusive interstitials also warns that popups covering the main content on mobile can make a page rank lower. On mobile, an inline sign-up box at the end of the article is the safer choice.

Make it worth the interruption

  • Offer something specific. A discount code, a checklist or the next article in a series works better than a generic “Subscribe”.
  • Make closing easy. A visible close button, the Escape key and a click on the backdrop should all close it.
  • Keep it short. One heading, one sentence, one field and a button.
  • Test it. Compare sign-ups and bounce rate with the popup on and off for a few weeks.

Common problems

  • The popup opens while moving over the page. mouseout also fires when moving between elements. Keep the relatedTarget check, which is only empty when the cursor leaves the document.
  • It opens when moving to a scrollbar or a second monitor. Add the clientY <= 0 check so only exits through the top count.
  • The close link jumps to the top of the page. The href="#" link scrolls to the top. Use a <button>, or call event.preventDefault() in the click handler.
  • It never appears while testing. You’ve already seen it once. Clear the exitPopupSeen key in your browser’s developer tools, under Application, then Local Storage.

Frequently asked questions

Do exit intent popups work? They can recover some visitors who would otherwise leave, mostly for email sign-ups and abandoned carts. Shown once with a clear offer, they cost little. Shown on every page, they push visitors away.

Can I build this without jQuery? Yes. The <dialog> version above uses no jQuery at all.

For more on detecting when the cursor leaves the window, see triggering a function on mouse leaving the browser.