Step 4
The script.js
contains a partial implementation of the Tic-Tac-Toe game. Your task is to complete the code.
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 the class name of "cell
".
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 are simply saying 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 to listen for
- 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) 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);
}
Feel free to experiment with the above simplistic implementation of game
; every time user clicks on a cell, its id
attribute will be printed to the console
.