Switching colors

when i push on button the background of <div>1</div> is yellow, when i push it second time background of <div>2</div> is yellow and <div>1</div> is white but when i do it third time <div>3</div> background wont change why is this?

    <script lang="javascript">
        
        var bool = false;
    function ChangeColor(){
        
        var first = document.getElementById("first");
        var second = document.getElementById("second");
        var third = document.getElementById("third");
        
        if (bool == false){
            first.style.background = ("yellow");
            bool = true;
        }else if (bool == true){
            first.style.background = ("white");
            second.style.background = ("yellow");
        }else if (bool == true){
            second.style.background = ("white");
            third.style.background = ("yellow");
        }
    }  
    </script>
</head
<body
    <div id="first">1</div 
    <div id="second">2</div
    <div id="third">3</div
    <button onclick="ChangeColor()"change</button
</body
</html>

I wouldnt use ‘bool’ as a variable name, because it’s a keyword for a type of variable.

Else…if stops if it finds something that is true.

if (true) {
  //Executed
} else {
 //Not executed
}

so

if(false) {
  //Not Executed
} else if (true) {
 //Executed
} else {
 //Not executed.
}

Because the second if evaluated to true, the third if never gets checked, it is skipped over. Specifically, javascript doesnt recognize a concept of “elseif”, it is just you tacking an if statement into the else block. You could write the same block as:

//Assume bool = true.
    if (bool == false){ //Not Executed.
        first.style.background = ("yellow");
        bool = true;
   } else { //Executed
        if (bool == true) { //Executed
          first.style.background = ("white");
          second.style.background = ("yellow");
       } else { //Not Executed.
            if (bool == true){
               second.style.background = ("white");
               third.style.background = ("yellow");
            }
      }
  }
}   
1 Like

Because when bool is true your program only runs into the 2nd condition, never the 3rd. You might use a counter variable instead like so:

var colorSwitch = 0
var first = document.getElementById('first')
var second = document.getElementById('second')
var third = document.getElementById('third')

function changeColor () {
  
  // Perform actions depending on the value 
  // of the color switch
  switch (colorSwitch) {
    case 0:
      first.style.background = ('yellow')
      break
    
    case 1:
      first.style.background = ('white')
      second.style.background = ('yellow')
      break

    case 2:
      second.style.background = ('white')
      third.style.background = ('yellow')
      break

    default:
      // Do nothing?

  }

  // Increment the color switch
  colorSwitch++
}

Edit: ah got ninja’d by @m_hutley. :-)

1 Like

now only the first one change to yellow?

Works for me… please post your full code (HTML + JS) so we can see what’s wrong.

    <script lang="javascript">

        function ChangeColor(){
              
        var colorSwitch = 0
        var first = document.getElementById("first");
        var second = document.getElementById("second");
        var third = document.getElementById("third");
        
            switch (colorSwitch) {
                case 0:
                    first.style.background = ("yellow");
                    break;
                
                case 1:
                    first.style.background = ("white");
                    second.style.background = ("yellow");
                    break;

                case 2:
                    second.style.background = ("white");
                    third.style.background = ("yellow");
                    break;
  }
  colorSwitch++;
}
    </script>
</head>
<body>
    div id="first">1</div>    
    div id="second">2</div>
    div id="third">3</div>
    button onclick="ChangeColor()">change</button>
</body>
</html>

and if my english is bad sorry

You declare the colorSwitch variable inside the changeColor() function, so each time the function gets called, you’re declaring it anew with the initial value of 0 (and discarding it after the function execution finished). You have to pull it out of the scope of that function to keep it across multiple function calls.

PS: I see you have your JS in the head… in the majority of cases it’s better placed at the very end of the body. This way, the DOM is fully available to the JS and you can pull the .getElementById() queries out of the function too, so that you don’t have to query for those elements anew each time the function gets called (like in my snippet above).

but you did it too? or did i not see it

i did what you said but still, only background 1 is working i dont see the fault

aaaah i see the fault

function ChangeColor(){

    var colorSwitch = 0
    var first = document.getElementById("first");
    var second = document.getElementById("second");
    var third = document.getElementById("third");

its inside the function i did it outside and it works now

i want to add somthing like a loop is this correct?

        if(true){
    
        switch (colorSwitch) {
            case 0:
                first.style.background = ("yellow");
                break;
            
            case 1:
                first.style.background = ("white");
                second.style.background = ("yellow");
                break;

            case 2:
                second.style.background = ("white");
                third.style.background = ("yellow");
                break;

}
}

You mean like cycling through the elements? Then you might use a modulo in the counter increment:

colorSwitch = (colorSwitch + 1) % 3

(An if (true) { } condition is generally pointless; the code will always get executed, so you could just as well omit it.)

You could then actually replace the switch / case with a loop over the elements you want to highlight like so:

<div class="highlight">First</div>
<div class="highlight">Second</div>
<div class="highlight">Third</div>
<button id="change">Change</button>
var colorSwitch = 0
var highlightEls = document.querySelectorAll('.highlight')
var change = document.getElementById('change')

function changeColor () {
  for (var i = 0; i < highlightEls.length; i++) {
    if (i === colorSwitch) {
      highlightEls[i].style.background = 'yellow'
    } else {
      highlightEls[i].style.background = 'white'
    }
  }

  colorSwitch = (colorSwitch + 1) % highlightEls.length
}

change.addEventListener('click', changeColor)

That makes your code easier to extend in case you want to add more elements to highlight.

1 Like

thank you so much man!!

No worries. :-)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.