Blog>
Snippets

Exit-Intent Modal

Detect user's intent to leave the page (e.g., by moving the cursor towards the close button or tab) and display a modal as a last engagement opportunity.
<!-- HTML -->
<div id="exitIntentModal" class="modal">
  <div class="modal-content">
    <span class="close-button">&times;</span>
    <h2>Wait! Before you go...</h2>
    <p>Here's an exclusive offer for you!</p>
    <!-- Your promotional content here -->
  </div>
</div>
HTML structure for the modal that will pop up when an exit intent is detected.
/* CSS */
.modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); }
.modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; }
.close-button { color: #aaa; float: right; font-size: 28px; font-weight: bold; }
.close-button:hover, .close-button:focus { color: black; text-decoration: none; cursor: pointer; }
CSS styles for the exit intent modal dialog.
// JavaScript
var modal = document.getElementById('exitIntentModal');
document.addEventListener('mouseout', function(event) {
  if (!modal.style.display && event.clientY < 50) {
    modal.style.display = 'block';
  }
});

var closeButton = document.querySelector('.close-button');
closeButton.addEventListener('click', function() {
  modal.style.display = 'none';
});
JavaScript code to show the modal when the mouse cursor leaves the upper boundary of the browser window, indicating an exit intent, and to close the modal when the close button is clicked.