pro78
pro78

Reputation: 75

Popup do not show after visitor come back to website

I have created a very simple popup window. What I would like is when the visitor come to the website for the first time to show the popup and he will have to choose one of the two buttons in order to close the popup. Moreover, I would like to do not show the popup box when the user has visited the site before. I know that I can use localstorage for that but I do not know the technique. Please, I need someone to write me the localstorage code that I have to add in my code so that when someone visits the website for the first time to show the popup and choose one of the two buttons, and if he comes back again to do not show the popup using localstorage memory.

Thanks

HTML:

    <div id="popup">
       <div id="text">
         Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque minus deleniti ex consequatur, rem, mollitia modi odit? Animi odit provident architecto omnis optio est, ut natus voluptatum, inventore deleniti laboriosam.
        </div>
        <div id="myButtons">
           <button id="button-left">Click Left</a>
           <button id="button-right">Click Right</a>
        </div>
   </div>

CSS:

 #popup {
            width: 30%;
            margin: 50px auto;
            padding: 50px;
            border: 10px solid #000;
        }

        #close-button {
            cursor: pointer;
        }

        #text {
            margin-top: 20px;
        }

        #button-left {
            display: inline-block;
            padding: 10px;
            background: #b4b0a9;
            float: left;
            margin-top: 10px;
        }

        #button-right {
            display: inline-block;
            padding: 10px;
            background: #b4b0a9;
            float: right;
            margin-top: 10px;
        }

JavaScript:

   var popup = document.getElementById("popup");
   var close_button = document.getElementById("close-button");
   var mainText  = document.getElementById("text");
   var button_left = document.getElementById("button-left");
   var button_right = document.getElementById("button-right");


    function closeBoxLeft() {
       popup.style.display = "none";
    }
    button_left.addEventListener("click", closeBoxLeft)

    function closeBoxRight() {
       popup.style.display = "none";
    }
    button_right.addEventListener("click", closeBoxRight)

Upvotes: 2

Views: 357

Answers (1)

Michael Coker
Michael Coker

Reputation: 53694

This is the general idea. Read in the popup item via localStorage.getItem(), and if it doesn't exist, show the popup and set popup via localStorage.setItem()

var ls = localStorage.getItem('popup');
if (!ls) {
  document.getElementById('popup').classList.add('show');
  localStorage.setItem('popup',true);
}
.popup {
  display: none;
}
.show {
  display: block;
}
<div id="popup" class="popup">popup</div>

Upvotes: 1

Related Questions