0

As you can see, I have a javascript which is supposed to make a darkmode switch on a website. javascript works I get the alert but nothing happens when I press the switch. Why? Note: I am very new to programming and stuff, so explanations for an idiot would be great. ----example.html----

  <a href="#" class="right">
    <button type="button" onclick="func()">Darkmode</button>
  </a>

---script.js---

let darkmode = 0
function func() {
    if(darkmode = 0){
        document.getElementById("main").style.background = "grey";
        document.getElementById("row").style.background = "grey";
        document.getElementById("footer").style.background = "grey";
        darkmode = 1;}
    else{
        document.getElementById("main").style.background = "white";
        document.getElementById("row").style.background = "white";
        document.getElementById("footer").style.background = "white";
        darkmode = 0;}
  }
alert("11 hot singles in your area");

----style.css---- (f.e. the main stuff from css)

  /* Main column */
  .main {   
    -ms-flex: 70%; /* IE10 */
    flex: 70%;
    background-color: white;
    padding: 20px;
  }
Avocadood
  • 3
  • 1
  • 1
    your `if` statement uses a single `=`. Meaning you're assigning instead of comparing a value. You need atleast two `==` to [compare values](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) – Reyno Jun 05 '21 at 13:18
  • Also note a simpler approach will be to toggle a class on the body and add css rules like `.darkmode .main, .darkmode footer, .darkmode .row{background-color:grey}` – charlietfl Jun 05 '21 at 13:21
  • And finally your css for `.main` is a class selector. `getElementById()` is for id not classes – charlietfl Jun 05 '21 at 13:24

2 Answers2

0

You got a very funny bug there

instead of if (darkmode = 0)

it should be if (darkmode === 0)

and that is just it

  • There is a close reason for typos. Answering typo issues provides no long term value to the knowledge base or future readers – charlietfl Jun 05 '21 at 13:26
0

There is an error in your js that when you compare you should put == instead of =. SO your js will be:

let darkmode = 0
function func() {
    if(darkmode == 0){
        document.getElementById("main").style.background = "grey";
        document.getElementById("row").style.background = "grey";
        document.getElementById("footer").style.background = "grey";
        darkmode = 1;}
    else{
        document.getElementById("main").style.background = "white";
        document.getElementById("row").style.background = "white";
        document.getElementById("footer").style.background = "white";
        darkmode = 0;}
  }
alert("11 hot singles in your area");
Kbs2021
  • 138
  • 11