Search code examples
javascripthtmlcookiesdarkmode

Storing settings in cookies


I have made a few settings but each time you refresh your page or go to another page on the website, those settings go back to default. How do i store the users settings in cookies so that they stay as they are when the user refreshes or enters another page? The settings are an option to switch to dark mode and an option to switch languages.

languages:

//html code//
<div class="language">
          <div class="langWrap">
            <a href="#"  language='dutch' class="lang active">NL</a>
            <a href="#"  language='english' class="lang">EN</a>
            <a href="#"  language='spanish' class="lang">ES</a>
            <a href="#"  language='indonesian' class="lang">ID</a>
          </div>
        </div>

//javascript code//
const langEl = [...document.querySelectorAll(".lang")];

let chosenLanguage = 'NL';

langEl.forEach((el) => {
    el.addEventListener("click", () => {
      langEl.map(item => item.classList.contains("active") ? item.classList.remove("active") : false);
      el.classList.add("active");
      chosenLanguage = el.innerText;
      search();
  
      const attr = el.getAttribute("language");
   });
});

dark mode theme:

//html code//
<img src="../images/moon.png" id="icon">

//javascript code//
var icon = document.getElementById("icon");

icon.onclick = function() {
  document.body.classList.toggle("dark-theme");
  if(document.body.classList.contains("dark-theme")){
    icon.src = "images/sun.png";
  } else {
    icon.src = "images/moon.png";
  }
}

Solution

  • I'm not sure the cookies are the best place to store user preferences. Cookies are sent to server so if you don't plan on storing those preferences on the server, it is useless extra network used. I think using localStorage suits more your needs.

    Anyway, w3schools gives two good functions to handle cookies in Javascript :

    function setCookie(cname, cvalue, exdays) {
      const d = new Date();
      d.setTime(d.getTime() + (exdays*24*60*60*1000));
      let expires = "expires="+ d.toUTCString();
      document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }
    
    function getCookie(cname) {
      let name = cname + "=";
      let decodedCookie = decodeURIComponent(document.cookie);
      let ca = decodedCookie.split(';');
    
      for(let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') {
          c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
          return c.substring(name.length, c.length);
        }
      }
    
      return null;
    }
    

    Now, if you want to use localStorage, the documentation of Mozilla is a good start.

    localStorage.setItem("darkmode", "true");
    var darkmode = localStorage.getItem("darkmode") === "true";
    

    Note that the localStorage only handles strings, unfortunately, thus the value "true" passed and checked as string.

    EDIT : Code style (null) and note about localStorage using strings