I am currently working on a portfolio website that features a light/dark mode theme switch. The functionality of the switch is working properly, but it doesn't save the user's preference when they refresh the page or navigate to another section. I would like the website to remember the state of the theme selection. I understand that I need to utilize localStorage to achieve this, but I'm having trouble implementing it.
Website: www.hermanvulkers.com
JavaScript code for the theme switch:
button.addEventListener("click", function () {
if (document.body.classList.contains("light-theme")) {
// Switch from light mode to dark mode
document.body.classList.toggle("light-theme");
document.getElementById('themeswitcher').innerHTML = `<span>Dark</span><img src="images/moon.png" alt="Choose website theme">`;
} else {
// Switch from dark mode to light mode
document.body.classList.toggle("light-theme");
document.getElementById('themeswitcher').innerHTML = `<span>Light</span><img src="images/sunrise.png" alt="Choose website theme"></img>`;
}
});
HTML code for the theme switch button:
<button class="themeswitcher" id="themeswitcher">
<span>Dark</span>
<img src="images/moon.png" alt="Choose website theme">
</button>
If anyone is able to provide assistance, I would greatly appreciate it. Thank you in advance!