Skip to content
Advertisement

Why doesn’t my JS update my data-theme back?

I want to have a button inside my navbar (ul li) that can toggle between theme=light and theme=dark. However, only activating dark mode works.

Code:

I created a button <li><a href="#" onclick="darkMode()"><i class="fas fa-moon"></i></a></li>, with a JS function

function darkMode () {
    var isOn = false;
    if(Boolean(isOn) === false) {
        document.documentElement.setAttribute('data-theme', 'dark');
        var isOn = true;
    }
    else if(Boolean(isOn) === true) {
        document.documentElement.setAttribute('data-theme', 'light');
        var isOn = false;
    }
}

and my css looks like this:

:root, [data-theme="light"] {
  --bg-color: #ffffff;
  --bg-color-inv: #000000;
  --outline-color: #000000;
  --text-primary: #000000;
  --text-primary-inv: #ffffff;
  --text-secondary: #a4a4a4;
  --text-secondary-hover: #000000;
  --chivo: 'Chivo', sans-serif;
}

[data-theme="dark"] {
  --bg-color: #121212;
  --bg-color-inv: #ffffff;
  --outline-color: #ffffff;
  --text-primary: #ffffff;
  --text-primary-inv: #000000;
  --text-secondary: #5b5b5b;
  --text-secondary-hover: #ffffff;
}

Advertisement

Answer

1. You start the function by setting the isOn to false. so Boolean(isOn) === false alwaeys return true. you should init the isOn variable outside the function

2 Why you convert the isOn to boolean? it’s already boolean type..

3 You not really need else if.. if it is not false it is true..

4. as mentioned in the comment below, not need reinitiate the isOn inside the if else

var isOn = false;

function darkMode () {
    if(!isOn) {
        document.documentElement.setAttribute('data-theme', 'dark');
        isOn = true;
    }
    else {
        document.documentElement.setAttribute('data-theme', 'light');
        isOn = false;
    }
}

in even more elegant way, you can do:

var isOn = false;

function darkMode () {

    document.documentElement.setAttribute('data-theme', ['dark', 'light'][+isOn]);
    isOn = !isOn;

}

explanation

+isOn convert it to number, so true become 1 and false become 0. Then you use this number as index to choose dark or light accordingly.

isOn=!isOn flip the current value of isOntrue become false and false become true

Advertisement