Search code examples
jquerycssbackground-colorclassname

jquery switch not changing css (3 colors)


Do you see what I need to change in this code?

    <style>
    .bgColor1{background: red !important;}
    .bgColor2{background: blue !important;}
    .bgColor3{background: green !important;}
    </style>

    <button onclick="mySwitch()">SWITCH COLOR</button>
    <script>
    function mySwitch() {
       jQuery('.background').each(function(){
       var classes = ['bgColor1','bgColor2','bgColor3'];
       jQuery('.background').className = classes[($.inArray(jQuery('.background').className, classes)+1)%classes.length];
      });
    });
  </script>

Below works for only 2 colors toggleclass:

    <button onclick="jQuery('.background').toggleClass('bgColor2')">toggle bg</button>

But I guess a toggleClass is for ONLY 2 colors, not 3 :(


Solution

  • You need to cycle through your classes using the modulo operator. I have produced a working example here

    HTML:

    <div id="background" class="bgColor0">
      <button id="but">SWITCH COLOR</button>
    </div>
    

    JavaScript:

    let counter = 0;
    $('#but').click(function () {
    
      $('#background').removeClass('bgColor' + ((counter % 3))); // Remove the previous color's class
      $('#background').addClass('bgColor' + ((counter + 1) % 3)); // Add the new colors class
    
      counter++;
    
    });
    

    CSS:

    #background {
      width: 200px;
      height: 200px;
    }
    
    .bgColor0{ background: red !important; }
    .bgColor1{ background: blue !important; }
    .bgColor2{ background: green !important; }