mercredi 3 mars 2021

How do I toggle between even/odd elements for a tic-tac-toe game

I have a function that adds a class oPiece while the counter is even and the class xPiece while odd. The current for-loop however only adds the class xPiece every time I click a div (with class=box)

JS

$('.box').click(function() {
  for (var i = 0; i < 8; i++) {
    if (i % 2 == 0) {
      $(this).addClass('oPiece');
    } else {
      $(this).addClass('xPiece');
    }
  }
});

HTML

<div class="container">
  <div class="box" id="1"></div>
  <div class="box" id="2"></div>
  <div class="box" id="3"></div>
  <div class="box" id="4"></div>
  <div class="box" id="5"></div>
  <div class="box" id="6"></div>
  <div class="box" id="7"></div>
  <div class="box" id="8"></div>
  <div class="box" id="9"></div>
</div>
<button class="resetBtn">Reset</button>

CSS

.container {
  width: 240px;
  height: 240px;
  border: 2px solid gray;
  display: block;
  padding: 0;
  font-size: 0;
  margin: auto;
}
.box {
  width: 80px;
  height: 80px;
  box-sizing: border-box;
  border: 1px solid gray;
  display: inline-block;
  align-items: center;
  justify-content: center;
}
.oPiece {
  background-color: blue;
}
.xPiece {
  background-color: red;
}
.resetBtn {
  display: block;
  margin: 20px auto;
}

Here is the link to my codepen --> https://codepen.io/jdk301/pen/LYbeeOX

Aucun commentaire:

Enregistrer un commentaire