I have a toggle button that switches between light / dark mode.
When toggled off, the "mode" local storage key is set to light, when on, "mode" is set to "dark-mode". Or at least that is what is supposed to happen. What ACTUALLY happens is that "mode" is set to light, and never changes to "dark-mode" (I’m monitoring this in the browser dev console).
When the button is toggled, the page does switch between dark and light mode, the problem is that when the page is refreshed, it defaults to light mode due to the issue described above.
My code:
$(document).ready(function() {
const checkbox = document.getElementById("checkbox")
checkbox.addEventListener("change", () => {
document.body.classList.toggle("dark-mode")
if (document.body.classList == "dark-mode") {
localStorage.setItem('mode', 'dark-mode');
} else {
localStorage.setItem('mode', 'light');
}
});
let mode;
mode = localStorage.getItem('mode');
if (mode === 'light') {
lightMode();
} else {
darkMode();
}
function darkMode() {
document.body.classList.add("dark-mode");
localStorage.setItem('mode', 'dark-mode');
mode = localStorage.getItem('mode');
}
function lightMode() {
document.body.classList.remove("dark-mode");
localStorage.setItem('mode', 'light');
mode = localStorage.getItem('mode');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<input type="checkbox" class="checkbox" id="checkbox">
<label for="checkbox" class="checkbox-label">
<i class="fas fa-moon" title="Dark Mode"></i>
<i class="fas fa-sun" title="Light Mode"></i>
<span class="ball" title="Toggle Light / Dark Mode"></span>
</label>
Thanks in advance for your help!
2
Answers
This happens because the code is missing updating the checkbox initialization after the page load.
You can fix this by
checkbox.setAttribute('checked', '');
following after #17.lightMode();
prefer something like this way:
HTML
CSS
JS