Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
my tic-tac-toe game if condition doesn't work

let cells = document.querySelectorAll(".cell");

let turn = "x";

cells.forEach( box => {
    box.addEventListener("click",
     () => box.classList.add("fill-" + turn));   

     if ( turn === "x" ) turn = "o";
     else turn = "x";
     
},
 { once: true}
);
#board{
  border: 2px solid red;
  width: 210px;
  height: 210px;
  margin: auto;
  
  
}

.cell{
  border: 1px solid red;
  display: block;
  background-color: rgb(241, 239, 239);
  text-decoration: none;
  width: 68px;
  height: 68px;
  float: left;
  cursor: pointer;
  font-size: 60px;
  text-align: center;
  line-height: 60px;
}

.cell:hover{
  background-color: rgb(207, 207, 207);

}

.cell.fill-x::after{
  content: "x";
  color: blue;
}

.cell.fill-o::after{
  content: "0";
  color: red;
}
<!Doctype html>
<html>
 <head>
  <title>Dooz</title>
  <meta charset="UFT-8">
  <link rel="stylesheet" href="dooz.css">
 
 </head>
 <body>
  
   <div id="board">
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
   </div>

   <script src="dooz.js"></script>
 </body>
</html>

I'm learning javascript and trying to build a tic-tac-toe game. I want to create an if condition to whether choose "x" or "o" after another, but my code doesn't work probably. inside second if statement line: when it's ( turn = "o" ), it only shows "o" when it's (turn === or == "o"), it only shows "x" What's the problem and how can I fix this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are using arrow function as second parameter in click event listener. Arrow functions can only run one statement if you don't specify a body using curly brackets.

let cells = document.querySelectorAll(".cell");

let turn = "x";

cells.forEach( box => {
    box.addEventListener("click",
     () => {
       box.classList.add("fill-" + turn));   

       if ( turn === "x" ) turn = "o";
       else turn = "x";
     });
},
 { once: true}
);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda