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