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");
}
} ```
Please make sure that your <script> is defined after the body tag (https://stackoverflow.com/a/9916754/18667225). Check for errors in F12-Console! In F12 Web-Storage tab you can also inspect the status of your key.
This simplified code works for me in Firefox:
<!DOCTYPE html>
<html>
<head>
</head>
<body onclick=toggle_theme()>
Hello World!
<body>
<script>
if (localStorage.getItem("theme")==null){
localStorage.setItem("theme", "light");
}
let localData = localStorage.getItem("theme");
if (localData == "light") {
alert("moon pre");
document.body.classList.remove("dark-theme");
}
else if (localData == "dark") {
alert("sun pre");
document.body.classList.add("dark-theme");
}
function toggle_theme() {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
alert("sun");
localStorage.setItem("theme", "dark");
}
else {
alert("moon");
localStorage.setItem("theme", "light");
}
}
</script>
</html>