Dark Theme Button

Hello dear Glitch users. I’m making a website on Glitch. I wanted to set a dark/light theme for my website, but my code isn’t working. Here my code:

HTML:

<button id="Theme" onclick="Theme()">
  Dark Theme
</button>
JS:

function Theme() {
 if (document.body.style.background == "#fefefe") {
   document.body.style.background == "#0a0a0a"
   document.getElementById ("Theme").innerHTML = "Light Theme"
 } else {
   document.body.style.background = "#fefefe";
   document.getElementById ("Theme").innerHTML = "Dark Theme"
 }
}

Can anyone help me, where is the problem? Thanks.

@eray6421, your JS looks fine (except for the space between document.getElementById and ("Theme")). Can you check if there are any errors in the browser DevTools?

There is not any error in browser DT. And the space isn’t a problem; JS requires this (even, I’ve tried the code without space, but nothing). I guess, problem is at the if, because I’have changed the default background color, and when I click the changing theme button, it changes background to #fefefe.

If that is the case, then try replacing background with backgroundColor.

First you’re missing some semicolons which probably isn’t helping, and more importantly document.body.style.background returns an rgb() CSS value not a hex color so your if statement never evaluates as true. I prefer stylistically to use a bool for toggling in this sort of situation.

I rewrote this and got it working, take a look here for reference.

<html>
  <body>
    <button id="Theme" onclick="Theme()">Dark Theme</button>

    <script>
      let isDark=false;
      document.body.style.background = "#fefefe";
      
      function Theme(){
        if (isDark){
          document.body.style.background = "#fefefe";
          document.getElementById("Theme").innerHTML = "Dark Theme";
          isDark = false;
        }
        else{
          document.body.style.background = "#0a0a0a";
          document.getElementById("Theme").innerHTML = "Light Theme";
          isDark= true;
        }
      }
    </script>
  </body>
</html>
1 Like

I tried that as well, it seems the browser will always implicitly convert to rbg regardless of the property accessed.

1 Like

What browser are you using? If none of these worked it could be how your browser handles JavaScript.

I think it’s a common issue, it didn’t work on Google Chrome.

1 Like

Thanks you very much! :slightly_smiling_face:

1 Like