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?
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.