I want the page to show popup when its loaded or refreshed. Upon clicking close button, popup should disappear and show me the page below. However, my code refreshes the page and displays popup again when I click close. How can I Fix this?
var popupDisplayed = "false" // localStorage.getItem("popupDisplayed");
window.addEventListener("load", function() {
if (popupDisplayed !== "true") {
var popupOverlay = document.getElementById('popup-overlay');
var popupGreeting = document.getElementById('popup-greeting');
popupOverlay.style.display = 'none';
popupGreeting.style.display = 'none';
setTimeout(function() {
popupOverlay.style.display = 'block';
popupGreeting.style.display = 'block';
}, 1000); // Reduced the delay to 1 second for demonstration purposes
//localStorage.setItem("popupDisplayed", "true");
}
});
document.querySelector("#closeButton").addEventListener("click", function() {
var popupOverlay = document.getElementById('popup-overlay');
var popupGreeting = document.getElementById('popup-greeting');
popupOverlay.style.display = 'none';
popupGreeting.style.display = 'none';
popupOverlay.style.opacity = '0';
popupGreeting.style.opacity = '0';
});
#popup-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9999;
}
#popup-greeting {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
text-align: center;
}
<div id="popup-overlay"></div>
<div id="popup-greeting">
<button id="closeButton">Close</button>
</div>
2
Answers
Solved! --
I used jquery to hide the popup, removed local storage and used prevent default function to solve the issue
Add button attribute ‘type="button"’ or you can also used ‘e.preventDefault()’ to stop page refresh.