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

Check if cookie exists and add style to class

I’m trying to get my script to check if a cookie exists. If it exists then set the class to display none, and when it does not exist then display block.

After pressing the button, the popup disappears, but after reloading the page, it is displayed again, despite the fact that the cookie still exists.

I have this script in my footer.

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

<script>
  setCookie = (cName, cValue, expDays) => {
    var date = new Date();
    date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
    var expires = "expires="+ date.toUTCString();
    document.cookie = cName + "=" + cValue + ";" + expires + "; path=/";
  }

  getCookie = (cName) => {
    const name = cName + "=";
    const cDecoded = decodeURIComponent(document.cookie);
    const cArr = cDecoded .split("; ");
    var value;
    cArr.forEach(val => {
      if (val.indexOf(name) === 0) value = val.substring(name.length);
    })
  }

  document.querySelector("#gdprCookiePopupAccept").addEventListener("click", () =>  {
    document.querySelector(".gdprCookiePopup").style.display = "none";
    setCookie("gdprAccept", true, 90)
  })

  var acceptCookie = getCookie("gdprAccept");

  if(acceptCookie !== 'null') {
    document.querySelector(".gdprCookiePopup").style.display = "block";
  } else {
    document.querySelector(".gdprCookiePopup").style.display = "none";
  };

</script>

what am I doing wrong?

>Solution :

The problem is that getCookie is returning undefined, as it’s returning nothing. Change it to:

 getCookie = (cName) => {
  const name = cName + "=";
  const cDecoded = decodeURIComponent(document.cookie);
  const cArr = cDecoded.split("; ");
  var value;
  cArr.forEach((val) => {
     if (val.indexOf(name) === 0) value = val.substring(name.length);
   });
  return value;
};

Also change your if statement to :

if (!acceptCookie) {
  document.querySelector(".gdprCookiePopup").style.display = "block";
} else {
  document.querySelector(".gdprCookiePopup").style.display = "none";
}

Because acceptCookie will never be equal to "null";

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