Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda