How to properly use a cookie in a javascript theme switcher?

Hello All!

I’d like to:

  1. add 2 additional themes to my site
  2. use javascript when switching from one to another
  3. store the setting in a cookie.

During the search process I found 2 great examples,

A big thank you to the authors!

So, with little js experience, I went through some tutorials to learn how to use cookies. Finally, I was able to put together a working example. Here’s the basic code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<style>
body {
  background-color: #00CC66;
}
body.dark {
  background-color: #000000;
}
body.light {
  background-color: #DCDCDC;
}
p {
  color: #000000;
}
.dark p {
  color: #FFFFFF;
}
.light p {
  color: #6699FF;
}
</style>
<script>
function setCookie(cvalue) {
  var d = new Date();
  d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = "theme=" + cvalue + ";" + expires + "; path=/";
}
function getCookie(theme) {
  var name = theme + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
function checkCookie() {
  var theme = getCookie("theme");
  if (theme == "default") {
  body.className = "";
  }
  if (theme == "light") {
  body.className = "light";
  }
  if (theme == "dark") {
  body.className = "dark";
  }  
}
</script>
</head>
<body>
<p>Test</p>
<button class="theme1">Default</button>
<button class="theme2">Dark</button>
<button class="theme3">Light</button>
<script>
var body = document.querySelector("body"),
goDefault = function () {
  body.className = "";
  setCookie("default");
},
goDark = function () {
  body.className = "";
  body.classList.add("dark");
  setCookie("dark");
},
goLight = function () {
  body.className = "";
  body.classList.add("light");
  setCookie("light");
};
document.querySelector(".theme1").addEventListener("click", goDefault, false);
document.querySelector(".theme2").addEventListener("click", goDark, false);
document.querySelector(".theme3").addEventListener("click", goLight, false);

checkCookie();
</script>
</body>
</html>

I tested it locally, so far it works perfectly. But since I’m not familiar with javascript I’m not sure whether I did it well or not. Could you tell me, please, is there anything obvious I should or should not use?

Any helpful advice is appreciated. Thank you in advance!

Hi @corolla88, I’d suggest to use the local storage instead of cookies as it is considerably easier to work with – cookies are only really necessary if you need to access the data on the server side as well. So using the web storage API you can just do

// Getting
var theme = window.localStorage.getItem('theme')
// Setting
window.localStorage.setItem('theme', 'dark')

BTW there’s also a string method to trim() whtespace, so you don’t need to that in a while loop:

theme = theme.trim()
1 Like

Hello, m3g4p0p,

thank you very much for the suggestion! I modified the script, it is very easy to understand and use! I also read some information about localStorage to get a basic knowledge. :ok_hand:

Thank you!

1 Like

Glad I could help! :-)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.