javascriptdomcookies

Saving user's cookie preference in JavaScript


I have this simple cookies banner that loads google analytics scripts if the user clicks on accept button. Then it remembers the choice for a month and does not show up again. However if the user clicks decline btn it asks him again as soon as the page is reloaded or visits another page on the site.

It would make sense that both user choices are saved for the month, so the user isn't forced to accept the cookies in the end.

    // COOKIES START
// ---- ---- Const ---- ---- //
const cookiesBox = document.querySelector(".privacy-container"),
  buttons = document.querySelectorAll(".button");
// ---- ---- Show ---- ---- //
const executeCodes = () => {
  if (document.cookie.includes("SlavicMedia")) {
    // If the cookie is already set, no need to show the cookie consent box
    loadGoogleAnalytics();
    return;
  }
  cookiesBox.classList.add("show");
  // ---- ---- Button ---- ---- //
  buttons.forEach((button) => {
    button.addEventListener("click", () => {
      cookiesBox.classList.remove("show");

      // ---- ---- Time ---- ---- //
      if (button.id == "acceptBtn") {
        document.cookie = "cookieBy= SlavicMedia; max-age=" + 60 * 60 * 24 * 30;
        loadGoogleAnalytics();
      }
    });
  });
};

What would the code modification look like to achieve desired functionality?

Thank you for your valuable inputs


Solution

  • See below:

    // COOKIES START
    // ---- ---- Const ---- ---- //
    const cookiesBox = document.querySelector(".privacy-container"),
          buttons = document.querySelectorAll(".button");
    
    // Function to check if a specific cookie is set
    const isCookieSet = (cookieName) => document.cookie.split(';').some((item) => item.trim().startsWith(cookieName + "="));
    
    // ---- ---- Show ---- ---- //
    const executeCodes = () => {
      // Check if any of the cookies are already set
      if (isCookieSet("SlavicMedia") || isCookieSet("DeclinedSlavicMedia")) {
        if (isCookieSet("SlavicMedia")) {
          loadGoogleAnalytics();
        }
        return;
      }
      cookiesBox.classList.add("show");
    
      // ---- ---- Button ---- ---- //
      buttons.forEach((button) => {
        button.addEventListener("click", () => {
          cookiesBox.classList.remove("show");
    
          // Set a cookie for a month based on the user's choice
          let cookieValue = button.id == "acceptBtn" ? "SlavicMedia" : "DeclinedSlavicMedia";
          document.cookie = `${cookieValue}=true; max-age=${60 * 60 * 24 * 30}`;
    
          // Load Google Analytics if accepted
          if (button.id == "acceptBtn") {
            loadGoogleAnalytics();
          }
        });
      });
    };
    
    // Call the function to initialize
    executeCodes();
    

    This checks to see if a cookie is already set, then set's the cookie based on whether they accept or decline, not just if they accept. Then the google analytics are only loaded if the accept cookie is set.