I am a working on a portfolio website that has a light/darkmode theme switch. The switch works, but it does not save the input. So when the user refreshes or clicks on a navigation link, the website goes back to the default lightmode. I want it to remember the state. I know that I have to use localStorage to make it work, but I can not seem to figure out how to do it.
Website: www.hermanvulkers.com
JavaScript theme switch code:
button.addEventListener("click", function () {
if (document.body.classList.contains("light-theme")) {
// Turn light mode off -> dark mode on
document.body.classList.toggle("light-theme");
document.getElementById('themeswitcher').innerHTML = `<span>Dark</span><img src="images/moon.png" alt="Choose website theme">`;
} else {
// Turn dark mode off -> light mode on
document.body.classList.toggle("light-theme");
document.getElementById('themeswitcher').innerHTML = `<span>Light</span><img src="images/sunrise.png" alt="Choose website theme"></img>`;
}
});
HTML button code:
<button class="themeswitcher" id="themeswitcher">
<span>Dark</span>
<img src="images/moon.png" alt="Choose website theme">
</button>
Is anyone able to help? Thanks in advance!