0

I'm trying to make a button that switchs the mode from light to dark. By default it's light mode, but for some reason, when I switch to dark mode, it works, but it won't switch back to light mode.

Here is the javascript code:

const modeButton = document.getElementById('light-dark-btn');

modeButton.addEventListener('click', ()=> {
    if(document.body.style.backgroundColor = 'rgb(255,255,255)'){
        document.body.style.backgroundColor = 'rgb(18,18,18)';
        document.body.style.color = 'rgb(255,255,255)';
    }else if((document.body.style.backgroundColor = 'rgb(18,18,18)')){
        document.body.style.backgroundColor = 'rgb(255,255,255)';
        document.body.style.color = 'rgb(0,0,0)';
    }
})

I'm trying to make a button that switchs the mode from light to dark.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
GrimmTVT
  • 3
  • 1

2 Answers2

0

The main problem here is that you're using = in the if statements instead of ===. But you're probably going to run in to some other problems with this approach, because the value of body.style.backgroundColor won't always exactly match what you set the style to. For example, I can add style="background-color: rgb(255,255,255)" to the body element. But if I run console.log(document.body.style.backgroundColor), I get rgb(255, 255, 255). Notice how it adds spaces between each number.

A more robust approach would be to just toggle a class on the body element, and use css to update the background and text colors.

Drew Pereli
  • 224
  • 1
  • 7
0

Two points needs to pay attention:

  1. need to use == instead of = when compare value,the latter one is assign value
  2. need to change rgb(18,18,18) to rgb(18, 18, 18),which means add white sopace between them,when debug,you will find it

const modeButton = document.getElementById('light-dark-btn');

modeButton.addEventListener('click', ()=> {
    let bgColor = document.body.style.backgroundColor
    if(bgColor == 'rgb(255, 255, 255)' || !bgColor){
        document.body.style.backgroundColor = 'rgb(18,18,18)';
        document.body.style.color = 'rgb(255,255,255)';
    }else if(bgColor == 'rgb(18, 18, 18)'){
        document.body.style.backgroundColor = 'rgb(255,255,255)';
        document.body.style.color = 'rgb(0,0,0)';
    }
})
<button id="light-dark-btn">Button</button>
flyingfox
  • 13,414
  • 3
  • 24
  • 39