I am making a Tic-Tac-Toe game using HTML, CSS, and JavaScript. I tried to add an event listener so to check whenever the button is clicked and added a condition to check whose turn it is. When clicked it should display the button is clicked and print the text according to the condition whenever the button is clicked.
let boxes = document.querySelectorAll(".box");
let turnO = true;
const winningPatterns = [
[0, 1, 2],
[0, 3, 6],
[0, 4, 8],
[1, 4, 7],
[2, 5, 8],
[2, 4, 6],
[3, 4, 5],
[6, 7, 8],
];
boxes.forEach((box) => {
box.addEventListener("onclick", () => {
console.log("box was clicked");
if (turnO) { //checking whether it is the turn O's turn
box.innerText = "O";
turnO = false;
} else {
box.innerText = "X"; //checking whether it is the turn of X's
turnO = true;
}
});
});
/* CSS added by Editor for demo purpose */
.game {
display: grid;
grid-template-columns: repeat(3, max-content);
grid-gap: 0.5em;
.box {
aspect-ratio: 1;
width: 2em;
}
}
<main>
<h1>Tic Tac Toe</h1>
<div class="container">
<div class="game">
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
</div>
</div>
<button id="reset-btn">Reset Game</button>
</main>
I want it to display whether the button is clicked and also whoever’s turn it is but the buttons are not working . I have connected my script file corectly with html. I want to know where I am making mistake.