Good evening! There was a problem with the solution of the problem. There are 9 blocks (an array of mult from 0 to 8). Task: to cyclically change the background of each block after a certain time interval. To change the background color there is a function colorChange (i, color). To her no complaints. The problem is that the background changes only during the first passage through the blocks from 0 to 8. Then, when the counter returns to its original value of 0, to walk through all the blocks again, the background color does not change anymore. Below is my code.

var mult = document.getElementsByClassName('mult'); function colorChange(i, color) { mult[i].classList.add(color); } var i = 0; var timerId = setInterval(function() { if (i != 0) { colorChange(i-1, 'white'); } if (i === 9) { i = 0; } colorChange(i, 'yellow'); i++; }, 300); 
  • What error do you see in the console? - tutankhamun

1 answer 1

Your problem is that once you add a class to elements, you do not delete it afterwards. Here is an example: if white added, then yellow is removed and vice versa.

  var mult = document.getElementsByClassName('mult'); function colorChange(i, color, dcolor) { mult[i].classList.add(color); mult[i].classList.remove(dcolor) } var i = 0; var timerId = setInterval(function() { if (i != 0) { colorChange(i - 1, 'white', 'yellow'); } if (i === 9) { i = 0; } colorChange(i, 'yellow', 'white'); i++; }, 300); 
 .white { background-color: white; } .yellow { background-color: yellow; } 
 <span class="mult">111</span> <span class="mult">222</span> <span class="mult">333</span> <span class="mult">444</span> <span class="mult">555</span> <span class="mult">666</span> <span class="mult">777</span> <span class="mult">888</span> <span class="mult">999</span>