Create a Custom Exit-Intent Popup for Your Website
Tags: webdev, javascript, tutorial, exitintentpopup
Published: 2023-09-24 09:46:04

Engaging with website visitors is essential for businesses and content creators looking to capture leads and boost user interaction. One effective way to do this is by implementing an exit-intent popup, a feature that triggers a popup when a user is about to leave the website. In this blog post, we'll walk you through the creation of a custom exit-intent popup for your website using JavaScript.

## Custom scenario for the new user when lands on the site

**Here's the scenario:**

1. The form is only on a contact form page.
2. If the user is on the contact page that has a form in it and the user navigates to other pages of the website and then the user tries to leave the site. We will trigger & show the popup.
3. This means I want to show an exit-intent popup only when the user has seen the form on the contact page and tries to leave the site if the user is on irrespective page of the site.

**Here's the logic I used:**

1. I want to trigger an exit-intent popup only when the user has seen the contact form on the website and tries to leave the site from any of the pages.
2. If the user has not seen the form, I will not trigger the popup.
3. I will use cookies, to perform this custom action on site.
4. If the user tries to leave the site after seeing the form. I will store two cookies for 30 days `formSeen` and `exitPopupShown`. 
5. If the user closes the exit-intent popup, I will store a cookie `closedExitPopup`.

### Implementation
Let's break down the key components:
- **Get Exit Popup & Close Button Element:** This code initializes variables for the exit popup element and the close button.

```
const exitPopupElement = document.getElementById('exit-popup')
const closeButton = document.getElementById('close-popup')
```
- **isFormVisible:** This function checks if a form is visible on the page. If a form is visible, it sets a cookie to indicate that the user has seen the form.

```
const isFormVisible = () => {
  const form = document.querySelector('.form')
  const checkDisplay = window.getComputedStyle(form).display
  if (checkDisplay === 'block' || checkDisplay === 'flex') {
    setCookie('formSeen', true, 30)
    return true
  }

  return false
}
```
- **validateExitPopup:** This function is called when the user attempts to exit the page. It checks if the user has seen the form, if the exit popup has not been shown before, and if the user has not closed the exit popup. If all conditions are met, it displays the exit popup and sets a cookie to indicate that the popup has been shown.

```
const validateExitPopup = () => {
  if (
    checkCookie('formSeen') &&
    !checkCookie('exitPopupShown') &&
    !checkCookie('closedExitPopup')
  ) {
    showExitPopup()
    setCookie('exitPopupShown', true, 30)
  }
}
```
- **showExitPopup:** This function sets the display property of the exit popup element to `'block'`, making it visible to the user.

```
const showExitPopup = () => {
  exitPopupElement.style.display = 'block'
}
```
- **closePopup:** When the user clicks the close button, this function hides the exit popup and sets a cookie to indicate that the popup has been closed.

```
// Close Popup
const closePopup = () => {
  exitPopupElement.style.display = 'none'
  setCookie('closedExitPopup', true, 30)
}
```
- **setCookie, getCookie, checkCookie:** These functions are used to manage cookies. They allow you to store and retrieve information about whether the user has seen the form, the exit popup has been shown, or the popup has been closed.

```
// setCookie function
function setCookie(cookieName, cookieValue, exdays) {
  const d = new Date()
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000)
  let expires = 'expires=' + d.toUTCString()
  document.cookie = cookieName + '=' + cookieValue + ';' + expires + ';path=/'
}

// getCookie function
function getCookie(cookieName) {
  let name = cookieName + '='
  let decodedCookie = decodeURIComponent(document.cookie)
  console.log(decodedCookie)
  let ca = decodedCookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) == ' ') {
      c = c.substring(1)
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length)
    }
  }
  return ''
}

function checkCookie(cookieName) {
  let cookieValue = getCookie(cookieName)
  return cookieValue !== ''
}
```
- **Event Listeners:** Event listeners are attached to relevant events. The DOMContentLoaded event triggers the isFormVisible function, the mouseleave event triggers the `validateExitPopup` function, and the close button's click event triggers the closePopup function.

```
window.addEventListener('DOMContentLoaded', isFormVisible)
document.addEventListener('mouseleave', validateExitPopup)
closeButton.addEventListener('click', closePopup)
```

### Customization

To customize this code for your website, follow these steps:

**HTML Markup:** Create the HTML structure for your exit popup and form. Make sure to add the appropriate id and class names for the elements you reference in the JavaScript code.

**Styling:** Style the exit popup and form using CSS to match your website's design.

**Cookie Expiry:** You can adjust the cookie expiration time (in days) by changing the exdays parameter in the setCookie function.

**Trigger Conditions:** Modify the conditions in the validateExitPopup function to match your desired trigger criteria. For example, you can change the condition related to the form's visibility to match a different element or condition on your website.

**Behavior:** Customize the behavior of your exit popup by modifying the showExitPopup and closePopup functions. You can add animations, delays, or other effects to enhance the user experience.

### Conclusion

Creating a custom exit-intent popup for your website can be a powerful tool for engaging with visitors and encouraging them to take specific actions. By using the provided JavaScript code as a foundation, you can tailor the popup to suit your website's needs and design. Be sure to test and iterate on your exit-intent popup to optimize its effectiveness in retaining visitors and converting them into leads or customers.

[GitHub Repository](https://github.com/azizqamar7/Custom-Exit-intent-Popup)

Let me know in the comment section if you think this can be improved 😊

Follow [@azizqamar7](https://www.twitter.com/azizqamar7) for more web development content.