'Can't change button value after setting it at load
I am trying to implement some code to make a darkmode switch for my website. I am stuck at changing the buttons value to the localstorage saved value. If it loads the value it cant be changed via the button later and if i remove it i need to click the button twice at load to get it to change from the initial wrong value. I get no error messages and don't know how to move forward.
My Javascript
function darkmode() {
theme = document.getElementById("themebutton");
if (theme.value == "Dark") {
theme.value = "Light";
document.documentElement.setAttribute("data-theme", "light");
localStorage.setItem("saved", "light");
} else if (theme.value == "Light") {
theme.value = "Dark";
document.documentElement.setAttribute("data-theme", "dark");
localStorage.setItem("saved", "dark");
}
function buttonvalue() {
document.getElementById("themebutton").value = saved;
}
buttonvalue();
window.onload = (event) => {
if (!localStorage.getItem("saved")) {
populateStorage();
} else {
setStyles();
}
};
function populateStorage() {
localStorage.setItem("saved", "light");
setStyles();
}
function setStyles() {
document.documentElement.setAttribute("data-theme", saved);
}
My button
<button type="button" id="themebutton" value="Light" onclick="darkmode();">
dark mode
</button>
Thanks in advance!
Solution 1:[1]
I found the problem. The var saved was in lower-case and the value was not. Fixed it by changing them to the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Erik Sandquist |
