I have a modal that triggers different on mobile vs. desktop. Mobile's popup is triggered by an inactive mouse for more than 10 seconds, and desktop's popup is triggered by the mouse leaving the page (mouseleave). However when I dismiss the modal on both devices, it reappears after the user does the triggered action again. How do I get the popup to only pop up once and not display again once the user dismisses it?
Here is my code:
Dismiss popup by adding class "hidden" on the modal, called #abandon-cart-message:
//Dismiss popup
function dismissModal() {
const dismissSelectors = [
"#abandon-cart-message .evg-btn-dismissal",
"#abandon-cart-message .button-cta",
];
Evergage.cashDom(dismissSelectors.join(",")).on("click", () => {
const dismissPopup = document.querySelector("#abandon-cart-message");
dismissPopup.classList.add("hidden");
});
}
Display popup function for inactive users, used for mobile
//display popup for inactive users
const inactiveUserMessage = () => {
//code for displaying the popup is tool specific so not showing code
console.log("popup displayed");
return dismissModal();
};
Display popup function for users when their mouse leaves the page, used for desktop
function exitUserMessage() {
//code for displaying the popup is tool specific so not showing code
console.log("popup displayed");
return dismissModal();
}
Trigger the actual popup
// Trigger popup for mobile
if (width <= 480) {
document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000), timer);
} else {
// Trigger popup for desktop
document.addEventListener("mouseleave", (e) => {
return exitUserMessage();
});
}
Debounce function, stored as a module from another file and pulled in:
export function debounce(func, timeout, timer) {
return (...args) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
}
Any ideas?
I tried to trigger a popup on mobile and desktop with both being triggered by different actions. However they are both reappearing after the user performs the same actions but I only want it to show one time once - if the user dismisses the popup it doesn't show again.
For JavaScript, you can use two ways two ways, Local Storage and Session Storage.
localStorage
store during sessions (after closing the browser the data remains)
To use it:
// Get value
const userDismissed = localStorage.get('dismissed');
// Check if is already dismissed
if( userDismissed && userDismissed === 'yes' ){
// Don't trigger
}
And to your dismiss function, define the localStorage
localStorage.setItem('dismissed', 'yes');
In case you need to reset the values
localStorage.clear(); // Remove all
localStorage.removeItem('dismissed'); // Remove just one item
sessionStorage
stores during the session is active (it resets when browser is closed)
To use it, it works same way than localStorage
above, just use sessionStorage
instead.