Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a popup <div> display only once per device?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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?

>Solution :

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.

Sidenote:

You can parse "false" with JSON.parse:

JSON.parse("false") // false

You can also use the Boolean constructor, though frowned upon:

Boolean("false") // false
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading