Exit intent popups, those annoying little windows that appear when you try to close a browser window, can be easily implemented by listening to a specific DOM event. While I personally find them annoying, there may be cases where your company requires you to implement one. In this tutorial, I will show you a simple way to create an exit intent popup using HTML, CSS, and JavaScript.
Let’s start with the HTML structure for the popup:
You can see the final implementation on CodePen here.
Once you load the page and move your mouse in and out, you should see the popup appearing after a second. The mouseout event is used to trigger the popup, and we added a delay of 1 second before showing it.
To enhance the functionality of the popup, you can add options to close it. For example, you can close the popup when the user presses the esc key:
//inside show() eventListener = document.addEventListener("click", function (clickEvent) { let el = clickEvent.target let inPopup = false if (el.id === 'popup') { inPopup = true } while (el = el.parentNode) { if (el.id == "popup") { inPopup = true } } if (!inPopup) hide() })
//inside hide() if (eventListener) { document.removeEventListener(eventListener) }
You can see an example of these additional features on CodePen here.
To ensure that the popup is only shown once to each visitor, you can store that information in a cookie. By setting the popup=true cookie when the modal is shown and checking for its existence before showing it again, you can control the frequency of the popup:
By leveraging this cookie-based implementation, you can make sure that the exit intent popup is shown only once per user.
I hope you found this tutorial helpful in creating your own exit intent popup. Feel free to experiment and enhance the functionality as per your requirements.