offline version 0.0.2


Cells activation in the find the number game in JavaScript

In the previous lesson, you had to make our build function return an array of table cells:

let cells = build(field, prepare(2)); console.log(cells);

Let's take this array, iterate over it and activate each cell. By activation, I mean that each cell background will turn red when you click on it.

However, according to the rules of the game, only the cell whose number goes in order should be activated. We need to consider this.

Move the activation code to a separate function:

let size = 2; let cells = build(field, prepare(size)); activate(cells);

First, let's do a simple cell activation in this function:

function activate(cells) { for (let cell of cells) { cell.addEventListener('click', function() { this.classList.add('active'); }); } }

And now we take into account the fact that cells can only be activated in order. To do this, we will introduce a counter that will store the number corresponding to the cell that can now be activated:

function activate(cells) { let counter = 1; // the counter for (let cell of cells) { cell.addEventListener('click', function() { this.classList.add('active'); }); } }

The further algorithm of actions will be as follows: if, when clicking on a cell, its text matches the counter, then we activate it and increase the counter by 1. And if it doesn't match, we don't activate it.

Complete the implementation of the described activate function.

enru