I have a small problem I have a theme switch button that turn the page to dark mode, but if I am in the home page and change to contact page the theme switch stops working, but this happens only on the other pages except the main one, and I don’t know how to fix it. I have tried to mess around with the js
code, but nothing.
Here is my JavaScript code:
// DarkMode
let darkmode = localStorage.getItem("darkmode")
const themeSwitch = document.getElementById("theme-switch")
const enableDarkmode = () => {
document.body.classList.add("darkmode")
localStorage.setItem("darkmode", "active")
document.getElementById("logo").src="../Imgs/logo-white.png"
}
const disableDarkmode = () => {
document.body.classList.remove("darkmode")
localStorage.setItem("darkmode", null)
document.getElementById("logo").src="../Imgs/logo-blue.png";
}
if (darkmode ==="active") enableDarkmode()
themeSwitch.addEventListener("click", () => {
darkmode = localStorage.getItem("darkmode")
darkmode !== "active" ? enableDarkmode() : disableDarkmode()
})
2
Answers
The error occurred because the theme-switch functionality also updates an image on the homepage. Since the image is only present on the homepage, attempting to modify it on another page where it doesn't exist resulted in a null value being returned.
Here is the updated code:
Thanks everyone for your time and sorry for wasting it
You are missing an else statement, so if you are in light mode, the light mode logo does not get displayed when a new page loads. Other than that, your code works fine for me.