So, I have several web pages and want them to stay dark, if dark mode is turned on on another page. So, I added one js script to all my HTML-files and it didn't work at all. After that, I tried to add this script to only one HTML-file and it stayed dark after reloading the page, but, obviously, it hadn't affected other pages.
How can I change the script to make it work and where is the problem?
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");
}
} ```