Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript if statement doesn't read condition

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading