skip to Main Content

I want to make JavaScript check my css code and return me if background color = #222327 it will change background color to #29fd53 But if old background color = #29fd53 it will change background color to #222327

My Js code

function changeBgC(){
var body = document.getElementsByTagName("body")[0];

var computedStyle = window.getComputedStyle(body)

var bodyBackgroundValue = computedStyle.getPropertyValue("background-color")
console.log(bodyBackgroundValue);
if (bodyBackgroundValue == "#222327") {
    document.querySelector('body').style.backgroundColor = "#29fd53"
  } else {
    document.querySelector('body').style.backgroundColor = "#222327"
  }
}
.body{
    width: 100%;
    height: 100vh;
    min-height: 100vh;
    background: #222327;
}
<div class="box">
<button onclick="changeBgC()" class="menuButton">≣</button>
</div>
          

I just try to use i++ (I use onclick on my html code) but it only changes the background color to #29fd53. When I press the button again it doesn’t do anything.

Here is what I try

function changeBgC(){
    var i = 0
    if (i % 2 === 0){
        document.querySelector('.body').style.backgroundColor = "#29fd53"
        console.log(i);
        i+=1
    }else{
        document.querySelector('.body').style.backgroundColor = "#222327"
        i+=1
    }
}

4

Answers


  1. Your problem lies in setting the i variable inside the function scope. So every time you call changeBgC() it will set i = 0.

    Declare i outside the function and it should work

    let i = 0;
    function changeBgC(){
        if (i % 2 === 0){
            document.querySelector('.body').style.backgroundColor = "#29fd53"
            console.log(i);
            i+=1
        }else{
            document.querySelector('.body').style.backgroundColor = "#222327"
            i+=1
        }
    }
    
    Login or Signup to reply.
  2. This can be achieved using a class instead of a function. This way the i variable can be encapsulated. I have used private members (#) as they are not required ouside of the class.

    class backg {
    
    #i=0;
    #elem=document.body.style;
    
    change() {
      this.#i=!this.#i;
      this.#elem.backgroundColor = this.#i?"#29fd53":"#222327";
     }
    }
    
    bkg=new backg();
    .body{
        width: 100%;
        height: 100vh;
        min-height: 100vh;
        background: #222327;
    }
    <div class="box">
    <button onclick="bkg.change();" class="menuButton">≣</button>
    </div>
              
    Login or Signup to reply.
  3. as @Teemu mentioned above getComputedStyle() returns an rgb() value
    so to get the HEX code you can use a css variable rather than writing a function to convert from RGB to HEX,

    trim function used to remove trailing spaces

    function changeBgC(){
      let bgColor = getComputedStyle(document.body).getPropertyValue('--bg-color').trim();
      if(bgColor == "#222327"){
        document.body.style.setProperty('--bg-color', '#29fd53');
      } else {
        document.body.style.setProperty('--bg-color', '#222327');
      }
    }
    body{
       --bg-color: #222327;
        width: 100%;
        height: 100vh;
        min-height: 100vh;
        background-color: var(--bg-color);
    }
    <div class="box">
      <button onclick="changeBgC()" class="menuButton">≣</button>
    </div>
    Login or Signup to reply.
  4. You should not use JavaScript to directly change the styles of elements for the purpose of switching themes.

    However, a better solution for switching themes is to use CSS variables instead of directly changing the styles of elements with JavaScript.

    This approach has several benefits, including better performance, easier maintenance, and more flexibility.
    Here’s an example of how you could use CSS variables to switch between light and dark themes:

    1. Use CSS variables for color changes:
    .theme-light {
      --bg-primary: #29fd53;
    }
    
    .theme-dark {
      --bg-primary: #222327;
    }
    
    body {
      background: var(--bg-primary);
    }
    
    1. Switching between themes:
    function switchTheme() {
        let themes = ['theme-light', 'theme-dark'];
        let currentTheme = [...document.body.classList].find(c => themes.includes(c)) ?? themes[0]
        let nextTheme = themes[themes.indexOf(currentTheme)+1] ?? themes[0]
        document.body.classList.remove(...themes) // removes all theme classes, including the current one
        document.body.classList.add(nextTheme)
    }
    
    1. HTML snippet:
    <div class="box">
      <button onclick="switchTheme()" class="menuButton">≣</button>
    </div>
    
    1. Don’t forget to add the initial class for the body with one of the themes:
    <body class="theme-light">
    
    <body class="theme-dark">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search