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?
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>