An attempt to write a tic-tac-toe game using JavaScript
P粉733166744
P粉733166744 2023-09-03 15:07:48
0
1
555
<p>I'm trying to implement the X's and O's in Tic Tac Toe via JavaScript by clicking a square on my board. I have to create X or O for Tic Tac Toe game. But I'm not sure how to make an X or an O. And I need it to be functional like an actual tic-tac-toe game. </p>
P粉733166744
P粉733166744

reply all(1)
P粉021708275

You have to iterate over each square because querySelectorAll returns multiple nodes and you can't add event listeners directly on it because addEventListener can only work on one node at a time.

I've also added some CSS to the code snippet below so you can see it working when you run it. Ignore this in the final project.

window.onload = () => {
    
    const squares = document.querySelectorAll(".square")

    let currentPlayer = "X";

    squares.forEach(square => {

        square.addEventListener("click", () => {
                
                if (square.innerHTML === "") {
                    square.innerHTML = currentPlayer;
                    currentPlayer = currentPlayer === "X" ? "O" : "X";
                }
    
            });
    });
};

document.querySelector('#reset-btn').addEventListener('click', () => {
    document.querySelectorAll('.square').forEach(square => {
        square.innerHTML = "";
    });
});
#board {
  margin: 0 auto;
  width: 50%;
}

.row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.square {
  border: 1px solid black;
  padding: 1rem;
  cursor: pointer;
  text-align: center;
  aspect-ratio: 1/1;
  
  display: flex;
  align-items: center;
  justify-content: center;
}

.square:hover {
  background-color: #CCCCCC;
}
<body>
  <div id="board">
    <div class="row">
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
    </div>
    <div class="row">
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
    </div>
    <div class="row">
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
    </div>
    <button id="reset-btn">RESET</button>
  </div>
</body>

Edit: I changed the above code snippet to alternate on click, which can be done by initializing a variable with the current player (X or O) and swapping on click using a simple ternary statement use. I also added functionality to your reset button!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template