Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

62
Vistas
Having trouble adding class to a div whilst building Tic Tac Toe game

I've looped through the divs and added event listeners to each of them. I'm now trying to add a class to the div when its clicked. I can successfuly add the class if i target the tile by ID but I want to add the class to the tile that is clicked.

var gameBoard = document.getElementsByClassName("tile")
var playerOne = {
"turn": true,
"class": "cross" 
}

var playerTwo = {
"turn": false,
"class": "naught" 
}
for (let i = 0; i < gameBoard.length; i++ ) {
gameBoard[i].addEventListener("click", takeTurn)
}


function takeTurn () {
this.classList.add(playerOne.class)
}

If I store a tile in a variable using getElementById then use

tileOne.classList.add(playerOne.class)

it works fine. but every div clicked would just change tile ones class and not the targeted click.

I'm still fairly new to programming so I think I'm missing something. Can anyone help?

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you add a listener you receive event data as arguments in the function called. So, you have to change your function takeTurn with:

function takeTurn (event) {
    event.target.classList.add(playerOne.class)
}

event.target select the element that trigger the event.

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.