Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda