Warm tip: This article is reproduced from stackoverflow.com, please click
css javascript local-storage

Change theme and store it in local storage

发布于 2020-03-27 10:17:40

I have two themes "dark" and "light", and I want the theme to change when clicking the checkbox.

This is how I changed the theme:

document.documentElement.setAttribute('data-theme', 'dark');

And now, this is working. But I want this change to be saved in local storage, thus even after reloading the page, the theme to stay as it is without changing.

here is my code:

checkBox.addEventListener('change', function () {
    if(this.checked) {

        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem( 'data-theme', 'dark');   
    }
    else {
        document.documentElement.setAttribute('data-theme', 'light');
        localStorage.setItem('data-theme', 'light');
    }
})

Did I made a mistake or is there something I don't understand?

Questioner
VenRus
Viewed
142
4,825 2019-07-03 21:48

May try it like this:

var checkBox = document.getElementById('cb');

var theme = window.localStorage.getItem('data-theme');
if(theme) document.documentElement.setAttribute('data-theme', theme);
checkBox.checked = theme == 'dark' ? true : false;

checkBox.addEventListener('change', function () {
  if(this.checked){
    document.documentElement.setAttribute('data-theme', 'dark');
    window.localStorage.setItem('data-theme', 'dark');
  } else {
    document.documentElement.setAttribute('data-theme', 'light');
    window.localStorage.setItem('data-theme', 'light');
  }
});
<input id="cb" type="checkbox" />
<label for="cb">Checkbox</label>