0

I have been trying to make a toggle button that when pressed, would turn the page black for my own eyes sake, but have been unable to do so. Here is how it looks when i try: https://gyazo.com/5cd21085350b603f9289bb5f64b2361e I'am not good with JavaScript so its not that complicated. I have my button that looks like this:

        <label class="switch" onclick="pagecolor();">
          <input type="checkbox">
          <span class="slider round"></span>
        </label>

And here is my JavaScript:

function pagecolor(){
    if(document.body.style.backgroundColor = "white") {
        document.body.style.backgroundColor = "black";
    } else {
        document.body.style.backgroundColor = "white";
    }
}

Hope you can help :)

Zigziig
  • 7
  • 1
  • A single equal sing (`=`) is used in assigning a value to a variable, for example `var x = 'white'`. For comparison, use double equal sign (`==`) for example `if (x == 'white'){ //code }else{//code}` – Clint_A Jun 30 '18 at 23:01

1 Answers1

2

Your if condition is incorrect, it always evalutes to true because you're asigning with single = sign, use ==

function pagecolor(){
    if(document.body.style.backgroundColor == "white") {
        document.body.style.backgroundColor = "black";
    } else {
        document.body.style.backgroundColor = "white";
    }
}
Ajanth
  • 2,435
  • 3
  • 20
  • 23
  • Just tried Lone Wolf but it did not work unfortunately :/ – Zigziig Jun 30 '18 at 22:58
  • Here is the working demo with my code : https://codepen.io/ajanth2012/pen/MXaPpp Perhaps something else is wrong with your code that you haven't shared – Ajanth Jun 30 '18 at 23:03
  • I did just check and it is my css that is causing the problem. Making the check box not matching with my button correctly so when clicked it did nothing – Zigziig Jun 30 '18 at 23:09