I'm working on a pretty simple JavaScript function to toggle a website between a light mode and a dark mode, and it's mostly coming along pretty well, but I've run into a pretty weird problem — the first time I want to change modes, I actually have to hit the toggle button twice.
This is the CSS I'm using...
<style type="text/css">
:root {
--textcolor: red;
}
p {
color: var(--textcolor);
}
</style>
...and this is my JavaScript...
<script>
function toggleColor() {
let color = document.documentElement.style.getPropertyValue("--textcolor");
if (color == "red") {
document.documentElement.style.setProperty("--textcolor", "green");
} else {
console.log("1");
document.documentElement.style.setProperty("--textcolor", "red");
}
}
</script>
The button isn't too complicated, so I can't imagine it's the issue, but just in case...
<button onclick="toggleColor()">Toggle</button>
The first time I load up my test page, the text displays as red, but when I click the toggle button, it logs that 1 and nothing changes... then when I hit the button again, it changes to green. After this first change, everything works fine, and it changes back and forth with just one click. Having to click a button twice isn't life or death, of course, but it would be annoying for users (some of whom might not bother trying twice), so I'd like it to work on the first try. Given the simplicity of this code, though, I honestly have no idea what could be wrong here...
In an attempt to figure it out, I made the JavaScript slightly more complicated...
<script>
function toggleColor() {
if (document.documentElement.style.getPropertyValue("--textcolor") == "red") {
document.documentElement.style.setProperty("--textcolor", "green");
} else if (document.documentElement.style.getPropertyValue("--textcolor") == "green") {
document.documentElement.style.setProperty("--textcolor", "red");
} else {
console.log("CSS error.");
}
}
</script>
...and my first click would always toggle that "CSS error" log — but after that first error message, the button would still work exactly as intended. This has me thinking that, for some reason, the JavaScript just isn't recognizing the property at all on the first click, but I still have no idea why.
Has anyone else encountered this error, and if so, how did you manage to solve it?