-1

I have a template that sets dark mode only adding a class to the body. This template does not include a toggle button so I am trying to create it by myself but it goes back to light theme when I go to another file or reload the page.

I am using a button and this JS code

var body = document.querySelector('body');
button.onclick = function(){
body.classList.toggle('dark-layout');
}

The problem is how can I save this settings, because once you reload it turns to the values set by default. I am sure there should be a front-end solution, but the only way I think is to create a table in a db and set the class inside an if and the button will be switching this value

  • 4
    have you try local storage or other front persistence mechanism ? – jeremy-denis Jan 04 '23 at 13:08
  • store in local storage, backend, or a cookie – depperm Jan 04 '23 at 13:08
  • 2
    Use JS Local Storage https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – Jan Pfeifer Jan 04 '23 at 13:09
  • FYI don't use querySelector to get the `body`, use `document.body` – vanowm Jan 04 '23 at 13:19
  • Does this answer your question? [Can not set current light/dark mode into local storage](https://stackoverflow.com/questions/72662122/can-not-set-current-light-dark-mode-into-local-storage) Down vote because this exact question gets asked at least once a month. Please research before asking. – Yogi Jan 04 '23 at 15:35

1 Answers1

2

A simplest solution is to use localStorage to store settings.

//read stored setting on startup
let isDarkMode = localStorage.getItem("darkmode");
//apply setting
setDarkMode();

button.onclick = function(){
  isDarkMode = !isDarkMode;
  setDarkMode(isDarkMode);
}
function setDarkMode(value = isDarkMode)
{
  value = ~~value; //convert to integer
  document.body.classList.toggle('dark-layout', value);
  localStorage.setItem("darkmode", value);
}

vanowm
  • 9,466
  • 2
  • 21
  • 37