Alternation of activation styles in JavaScript

In the previous lesson, we learned how to activate cells by clicking on them. Let's now make the colors alternate: let the first cell be painted red, the second cell green, the third cell red again, and so on.

To solve this problem, we need two CSS classes already:

.color1 { background: red; } .color2 { background: green; }

Let's implement the described alternation:

let tds = document.querySelectorAll('#table td'); let color = 'color1'; for (let td of tds) { td.addEventListener('click', function() { if (color == 'color1') { color = 'color2' } else { color = 'color1' } this.classList.add(color); }); }

Take a look at my code and then try this problem yourself.

Several colors alternation from an array

Let now we want to alternate not two colors, but an arbitrary number. Let's store an array of CSS classes for this:

let colors = ['color1', 'color2', 'color3'];

Let's write the colors for our classes:

.color1 { background: red; } .color2 { background: green; } .color3 { background: yellow; }

And now let's implement alternation:

let tds = document.querySelectorAll('#table td'); let i = 0; let colors = ['color1', 'color2', 'color3']; for (let td of tds) { td.addEventListener('click', function() { this.classList.add(colors[i]); i++; if (i == colors.length) { i = 0; } }); }

Tell me how my code works.

enru