Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save cookies for Dark/Light Mode Toggle?

I am using the W3Scholls Dark Mode Toggle for my webiste and it's working perfectly well.

But just after I refresh my page the default view that is Day Mode is shown.

This is Webpage Test Page.

How can I set cookies so that if a user selects dark mode then the page opens in dark mode by default?

Also, How can this be applied for the whole website so that the user need not press the button every time he opens the page.

like image 861
Andy Avatar asked Feb 03 '20 10:02

Andy


1 Answers

You could use localStorage for this.

// On page load set the theme.
(function() {
  let onpageLoad = localStorage.getItem("theme") || "";
  let element = document.body;
  element.classList.add(onpageLoad);
  document.getElementById("theme").textContent =
    localStorage.getItem("theme") || "light";
})();

function themeToggle() {
  let element = document.body;
  element.classList.toggle("dark-mode");

  let theme = localStorage.getItem("theme");
  if (theme && theme === "dark-mode") {
    localStorage.setItem("theme", "");
  } else {
    localStorage.setItem("theme", "dark-mode");
  }

  document.getElementById("theme").textContent = localStorage.getItem("theme");
}

HTML:

<button type="button" onclick="themeToggle()">Theme Toggle</button>
<div id="theme"></div>
like image 161
Sohail Ashraf Avatar answered Oct 23 '22 18:10

Sohail Ashraf