Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

71
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!