-3

Im trying to write a tic tac toe game with javascript and there is a mistake in the code that doesn't get displayed in the console can someone please tell me what is wrong with the script.

var box = document.getElementById("box");
var subBox = document.getElementsByClassName("subBox");
var num = 0;

function turn() {

  if (num % 2 == 0) {
    document.subBox.this.innerHTML = "X";
    num++;
  } else if (num % 2 == 1) {
    document.subBox.this.innerHTML = "O";
    num++;
  }

}

for (i = 0; subBox.length < i; i++) {
  subBox[i].addEventListener('click', turn());
}
epascarello
  • 204,599
  • 20
  • 195
  • 236

2 Answers2

0

You had a bunch of small problems preventing you from making your code work. First you are not looping correctly over your for loop. The logic was reversed so the loop was not running. The first iteration the if check was checking to see if 9 < 0. That is false so the events were never assigned.

You were calling click instead of assigning a reference to the element in the event listener.

Thirdly you were using the this reference wrong to get the element that was clicked to alter the text of the cell.

Below is the code with those issue corrected.

var subBox = document.getElementsByClassName("subBox");
var num = 0;

function turn() { 
  
  // reference element with this
  console.log(this);

  if (this.innerHTML.length) {
    return;
  } else if (num % 2 == 0) {
    this.innerHTML = "X";
  } else {
    this.innerHTML = "O";
  }
  num++;
}

// for loop was wrong
for (i = 0; i < subBox.length; i++) {
  // you assign turn, you do not execute it
  subBox[i].addEventListener('click', turn);
}
div.box {
  display: grid;
  grid-template-columns: repeat(3, 100px);
   grid-gap: 0px;
}

div.subBox {
  line-height: 100px;
  font-size: 30px;
  text-align: center;
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
<div class="box">
  <div class="subBox"></div>
  <div class="subBox"></div>
  <div class="subBox"></div>
  <div class="subBox"></div>
  <div class="subBox"></div>
  <div class="subBox"></div>
  <div class="subBox"></div>
  <div class="subBox"></div>
  <div class="subBox"></div>
</div>
epascarello
  • 204,599
  • 20
  • 195
  • 236
-1

You haven’t posted the data structure. What kind of element is subBox?

This line doesn’t look good either way…

document.subBox.this.innerHTML="X";

It should be…

subBox.innerHTML="X";

But if it’s a two-dimensional array then it should go…

subBox[x][y].innerHTML="X";

Needless to say that a one-dimension array should be...

subBox[x].innerHTML="X";
Dharman
  • 30,962
  • 25
  • 85
  • 135