JavaScript
Intermediate
Updated 5h ago
Exit Intent Popup Detection
Detect when a user is about to leave the page and trigger a popup.
<script>
function detectExitIntent(callback) {
let triggered = false;
document.addEventListener("mouseleave", function(e) {
if (e.clientY <= 0 && !triggered) { triggered = true; callback(); }
});
let lastScrollY = window.scrollY;
let scrollUpCount = 0;
window.addEventListener("scroll", function() {
if (window.scrollY < lastScrollY) {
scrollUpCount++;
if (scrollUpCount > 3 && window.scrollY < 100 && !triggered) {
triggered = true; callback();
}
} else { scrollUpCount = 0; }
lastScrollY = window.scrollY;
});
}
detectExitIntent(function() { console.log("User is about to leave!"); });
</script>
Technical Breakdown
Detects exit intent via mouse leaving top of viewport on desktop, and rapid scroll-up on mobile.
Pitfalls & Solutions
1. Triggering on every mouseleave. 2. No mobile detection. 3. Popup reappearing.
Tags
#JavaScript
#Popup
#Exit Intent