Issue
I have a div that should toggle dark mode on or off whenever it is clicked based on the number of times it has been clicked. However this code doesn't seem to work. The click count functions fine, it's just the if statement that is giving me issues.
let x = 0;
document.getElementById("darkmode").onmousedown = function darkMode(){
x+=1;
console.log(x);
}
if(x % 2 == 0){
document.body.style.backgroundColor = "#0A0A0A";
}
else {
document.body.style.backgroundColor = "white";
}
The colour of the background does not change at all. I tried using a simpler condition, (x == 5), in the if statement but that didn't work either. Any help is appreciated.
Solution
You're only checking the conditional on page load, not on button click. Move the conditionals inside of the event listener. Additionally, if the default page load is NOT darkmode, then set let x = 1;
to start so the first click toggles darkmode on.
Though as x
is just toggling between 2 values, it should probably be a boolean instead - let darkmode = false;
and instead of x++
you'd do darkMode = !darkMode;
let darkmode = false;
document.getElementById("darkmode").onmousedown = function darkMode(event) {
darkmode = !darkmode;
// move the conditional logic inside of the event function
if(darkmode){
document.body.classList.add('darkmode');
} else {
document.body.classList.remove('darkmode');
}
event.preventDefault();
}
.darkmode {
background-color: #0A0A0A;
}
.darkmode p {
color: white;
}
<a href="#" id="darkmode">Toggle darkmode</a>
<p>here is some content</p>
Answered By - WOUNDEDStevenJones
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.