Reputation: 15
So I've been trying to make a popup on the homepage of my website that gets displayed only the first time a device accesses my website, then, when it gets closed with a button it should not appear anymore. To do this thing I tried thousands of ways and snippets but no one worked.
This is my code right now:
html
<div class="popup" id="popup">
<!-- more elements for design purposes -->
<button class="allCookies" onclick="closePopup()">Close popup</button>
</div>
CSS
.popup {
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.1);
backdrop-filter: blur(8px);
z-index: 1;
}
JS
var popup = document.getElementById("popup");
var popupShown = localStorage.getItem("popupShown");
function closePopup() {
popup.style.display = "none";
localStorage.setItem("popupShown", "true");
}
if (popupShown === null || popupShown === "false") {
popup.style.display = "block";
}
I wanted the popup to get displayed only the first time I open that html page, altough the popup keeps displaying every time the page gets reloaded. Can someone please help me?
Upvotes: 1
Views: 343
Reputation: 333
In your CSS you set display: block
, I think you want to change that to display: none
or else the default will be, that it is always shown. Even if you don't set display to block in your javascript, it will already be so because of your CSS. Change that and it should be fine.
You can parse "false"
with JSON.parse
:
JSON.parse("false") // false
You can also use the Boolean
constructor, though frowned upon:
Boolean("false") // false
Upvotes: 1