I am trying to use localStorage to keep my theme consistent over page changes but I can't seem to get it to work.
This is what my html looks like:
<body onload="checkLightMode()">
<li><button class="mode-toggle"><i class="fas fa-sun fa-2x"></i></button></li>
There is also a second duplicate button for the mobile nav
And the JavaScript:
const button = document.querySelectorAll('.mode-toggle')
button.addEventListener('click', function () {
localStorage.setItem('light-mode', true)
if (localStorage.getItem('light-mode')) {
document.body.classList.toggle('light-mode')
document.querySelectorAll('.fa-sun').forEach(icon => icon.classList.toggle('fa-moon'))
} else {
document.body.classList.remove('light-mode')
localStorage.setItem('light-mode', false)
}
})
function checkLightMode() {
if (localStorage.getItem('light-mode')) {
body.classList.add('light-mode')
}
}
I can't use local storage in sandbox code snippet so I did it with variable, it should be the same concept.
const button = document.querySelector('.mode-toggle')
var isTrueSet = (value) => value === 'true';
let lightMode = false;
button.addEventListener('click', function () {
const v = localStorage.getItem('light-mode');
if (!lightMode) { // change to (!v && !isTrueSet(v))
document.body.classList.add('light-mode')
lightMode = true
} else {
lightMode = false
document.body.classList.remove('light-mode')
}
})
function checkLightMode() {
const v = localStorage.getItem('light-mode');
if (lightMode) { // (!v && !isTrueSet(v))
body.classList.add('light-mode')
}
}
body {
background-color: #000;
width: 100%;
height: 100%;
}
.light-mode {
background-color: #fff;
}
<div id="one" onload="checkLightMode()">
<li><button class="mode-toggle">mode</button></li>
</div>
I create a state.js file, which will be the first module that loads. (Following angular methodology).
There I put all global variables. I think it's easy to handle and suits your needs.
let lightMode = false;
const button = document.querySelector('.mode-toggle')
button.addEventListener('click', function () {
if (!lightMode) {
document.body.classList.add('light-mode')
lightMode = true
} else {
lightMode = false
document.body.classList.remove('light-mode')
}
})
function checkLightMode() {
if (lightMode) {
body.classList.add('light-mode')
}
}
With this method you would create this variable more than once, It's stays in an organized file, And it is easy to maintain.