Step 4
The script.js
contains some initial code to get you started. Your task is to complete the implementation of this game. But first, let's explore the content of script.js
. Here are the first few lines:
let cells = document.querySelectorAll(".cell");
cells.forEach(function (cell) {
cell.addEventListener("click", game);
});
The querySelectorAll
returns an array of all HTML elements with cell
class name.
The forEach()
method executes a provided function once for each array element. For clarity, let's rewrite the second statement:
cells.forEach(runGameOnClick);
function runGameOnClick(element) {
element.addEventListener("click", game);
}
In JavaScript, we can pass a function as a parameter to another function!
The original statement declares an anonymous function.
An anonymous function is a function without a name.
One common use for anonymous functions is as arguments to other functions.
cells.forEach(function (cell) {
cell.addEventListener("click", game);
});
Another way of writing anonymous functions is using arrow functions:
cells.forEach( (cell) => {
cell.addEventListener("click", game);
});
We will explore these alternative syntaxes to function declaration at a later time.
So, the first few lines say that the game
function must be called every time a user clicks on any of the cells (of the game board).
Note the addEventListener
method takes two arguments:
- A (case-sensitive) string representing the event type
- A function that will be called whenever the specified event is delivered to the target element.
In our solution, the addEventListener
will call the game
function when a user clicks on a cell. It will pass an object, event
, to the game
function. The event
object contains many properties about the specified event, including a reference to the target element (cell) in which the event occurred.
So, when a user clicks on a cell, you can access that cell and e.g. its id
attribute as follows:
function game(event) {
let cell = event.target;
console.log(cell.id);
}
Open the developer tools. When you click on a cell, its ID must be printed to the console.