I am currently working on adding a dark theme toggle to my website and can't seem to figure out the best way to store the data to LocalStorage. All I am using is a button that toggles the class of "dark" on the main document :root. The actual toggle works perfectly fine, I am only struggling with getting that selected option to stay in LocalStorage.
Here is my code with the LocalStorage that I am trying to add (which does save the key of theme to LocalStorage but not the actual class toggle).
document.addEventListener("DOMContentLoaded", function () {
const theme = localStorage.getItem("theme", "dark");
const darkModeToggle = document.getElementById("modeSwitch");
darkModeToggle.addEventListener("click", function () {
document.documentElement.classList.toggle("dark");
if (document.documentElement.classList.contains("dark")) {
localStorage.setItem("theme", "dark");
}
});
});
Here are my CSS variables as well for reference.
:root {
--main-background: #f8fafb;
--app-background: #ffffff;
--app-background-alt: #fcfcfc;
--app-background-hover: #f8fafb;
--dark-background: #141923;
--main-color: #000000;
--secondary-color: #747987;
}
.dark:root {
--main-background: #141923;
--app-background: #171b2c;
--app-background-alt: #1c2031;
--app-background-hover: #1d213d;
--dark-background: #141923;
--main-color: #ffffff;
--secondary-color: #747987;
}
Thank you so much.