I'm facing an issue with maintaining a dark mode across multiple web pages. I tried adding a JavaScript script to all my HTML files, but it didn't work as expected. Then, I experimented by adding the script to just one HTML file, and while it successfully kept that page in dark mode upon reload, it didn't affect other pages.
I need help figuring out how to modify the script so that it works consistently across all pages. Can someone identify the problem and suggest a solution?
Script:
if(localStorage.getItem("theme")==null){
localStorage.setItem("theme", "light");
}
let localData = localStorage.getItem("theme");
if (localData == "light") {
icon.src = "images/moon.png";
document.body.classList.remove("dark-theme");
}
else if (localData == "dark") {
icon.src = "images/sun.png";
document.body.classList.add("dark-theme");
}
icon.onclick = function () {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
icon.src = "images/sun.png";
localStorage.setItem("theme", "dark");
}
else {
icon.src = "images/moon.png";
localStorage.setItem("theme", "light");
}
}