Hello everyone! I’m working on a project at the website https://en.nomorigine.com/ where I want to show a popup when a user tries to leave the page. Although I have the basic popup code set up, I’m unsure how to properly trigger it using JavaScript right before a user exits the site. I previously attempted to utilize the unload function from jQuery, but I was not successful. Can anyone suggest an alternative approach? Below is my existing code sample:
To trigger a popup when a user attempts to leave a page, the beforeunload
event can indeed be useful, but it behaves differently depending on the browser. Here’s a more reliable approach using JavaScript:
Solution:
<script>
(function() {
var storageKey = 'newsletter'; // Key for localStorage.
var popupSelector = '#show-newsletter'; // Selector for the popup.
function attemptPopupDisplay() {
// Check if the popup has already been shown today using localStorage.
if (window.localStorage) {
var nextShowTime = parseInt(localStorage.getItem(storageKey), 10);
if (nextShowTime && nextShowTime > Date.now()) {
return;
}
var expiryTime = new Date();
expiryTime.setHours(expiryTime.getHours() + 24);
localStorage.setItem(storageKey, expiryTime.getTime());
}
DiviPopup.openPopup(popupSelector);
}
// Use the 'mouseleave' event for a better UX approach
document.addEventListener('mouseleave', function(e) {
// Check if the mouse leaves from the top of the page (likely intent to close the tab or window)
if (e.clientY < 0) {
attemptPopupDisplay();
}
});
})();
</script>
Explanation:
- The
mouseleave
event is used on thedocument
to detect when the mouse leaves the top of the page. This could be a more user-friendly indication that the user intends to close the tab/window. - The timestamp in
localStorage
helps in controlling the frequency of popup display. - Ensure your popup triggering method
DiviPopup.openPopup()
exists in your script and works as expected.
Note: The beforeunload
event is mainly for preventing accidental navigation, and modern browsers have limited its use to prevent unwanted popups without user interaction.