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.

<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";

Leave a Reply