I'm trying to toggle between a moon icon and a sun icon on a dark mode project. The original javascript code was simply a button that switched from day mode to dark mode. After some research, I ended up with the following code, which "kinda" works but is sketchy; it switches from day mode to dark mode and the icon toggles from moon to sun BUT, when I come back to the page after setting my preference as dark mode (or refreshing the page in dark mode), the icon disappears.
const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
document.body.classList.toggle("dark-theme");
icon.classList.toggle("fa-sun-o");
} else if (currentTheme == "light") {
document.body.classList.toggle("light-theme");
icon.classList.toggle("fa-moon-o");
}
btn.addEventListener("click", function () {
if (prefersDarkScheme.matches) {
document.body.classList.toggle("light-theme");
var theme = document.body.classList.contains("light-theme")
? "light"
: "dark";
icon.classList.toggle("fa-sun-o");
} else {
document.body.classList.toggle("dark-theme");
var theme = document.body.classList.contains("dark-theme")
? "dark"
: "light";
icon.classList.toggle("fa-moon-o");
}
localStorage.setItem("theme", theme);
});
Any idea what I am missing here?
I created a codepen to show the issue