DanG
DanG

Reputation: 197

Use cookies to only show my pop up only once?

I'm struggling to add cookie control to my popup so it only shows once.

 var modal = document.querySelector(".modal");
 var close = document.getElementById("myDiv");
 var element = document.getElementById("myDiv");

 function popupScroll() {
    element.classList.add("show-modal");
 }
 function closeModal() {
    element.classList.add("hide-modal");
 }
 window.addEventListener("scroll", popupScroll);
 window.addEventListener("click", closeModal);

Upvotes: 0

Views: 892

Answers (2)

Oscar R
Oscar R

Reputation: 154

I advice to use localStorage. Its a Javascript API with functions like setItem and getItem. Here an example:

function displayPopup() {
  //if the variable in localStorage is set dont show the popup and just return
  if (localStorage.getItem('popupAlreadyShown')) return;

  //display popup, example: 
  document.getElementById('popup').style.display = 'block';
}

function closePopup() {
  //close popup, example: 
  document.getElementById('popup').style.display = 'none';
  //set the variable in localStorage that the popup is closed
  localStorage.setItem('popupAlreadyShown', 'true');
}

Upvotes: 1

Harshith Rai
Harshith Rai

Reputation: 3066

You could use localStorage or sessionStorage.

While localStorage accesses the current domain's local Storage object and adds a data item to it, sessionStorageaccesses the current domain's session Storage object and adds a data item to it.

    var modal = document.querySelector(".modal");
    var close = document.getElementById("myDiv");
    var element = document.getElementById("myDiv");

    function popupScroll() {
        if (!localStorage.getItem('showPopup')) { //check if popup has already been shown, if not then proceed
            localStorage.setItem('showPopup', 'true'); // Set the flag in localStorage
            element.classList.add("show-modal");
        }
    }
    function closeModal() {
        element.classList.add("hide-modal");
    }
    window.addEventListener("scroll", popupScroll);
    window.addEventListener("click", closeModal);

Remember, while an item that has been set in sessionStorage lasts as long your browser session, the localStorage items don't have expiration times. That being said, in your current case, you could use either localStorage or sessionStorage.

Upvotes: 1

Related Questions