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

72
Vistas
Broken addEventListener method for cookie popup

I need advice on how to fix the addEventListener function in the js cookie code for my website. The cookie popup always appears, but when I click the Agree button, it doesn't disappear and is not written to local storage. The console writes me this: "Uncaught TypeError: Cannot read property 'addEventListener' of null". I would like someone to help me with this, I don't know how to deal with it. Below the text is the js code and the html code.

JS Code:

const cookieContainer = document.querySelector(".cookie-container");
const cookieButton = document.querySelector(".cookie-btn");

cookieButton.addEventListener("click", () => {
  cookieContainer.classList.remove("active");
  localStorage.setItem("cookieBannerDisplayed", "true");
});

setTimeout(() => {
  if (!localStorage.getItem("cookieBannerDisplayed")) {
    cookieContainer.classList.add("active");
  }
}, 2000);

HTML Code:

<div class="cookie-container">
        <p>
            Používáním této stránky souhlasíte s ukládáním souborů cookies a sběrem dat.
        </p>
        <button class="cookie-btn">Souhlasím</button>
    </div>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need to set the container's default display to none and only set it to block when it has the active class.

Demo

about 4 years ago · Juan Pablo Isaza Denunciar

0

suggestion:

if(cookieButton) {
  cookieButton.addEventListener("click", () => {
    cookieContainer.classList.remove("active");
    localStorage.setItem("cookieBannerDisplayed", "true");
  });
}

// Edit:
setTimeout(() => {
  if (!localStorage.getItem("cookieBannerDisplayed")) {
   if(cookieContainer)
    cookieContainer.classList.add("active");
  }
}, 2000);

I presume if accepted, your div is not in the dom of the page. So unable to find your button.

<div class="cookie-container">
...
</div>
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