Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Something like TIC TAC TOE in JavaScript

I was thinking to do a simple tic tac toe game, but instead of adding X and 0, I was thinking when a square is clicked, that square should become red, then next click on another square to make it blue.

All was ok, until the squares turn only into red when I click on them and on next click they don't became blue. I tried different ways, without success. Finally I wrote the code like so, to be very clear that after .red class was added on the div that was clicked, the value of current player should change, and then because it changed, on next click to add the .blue class on clicked div. But it's becoming red, not blue. What should I do, so on next click the div should turn into blue? Thanks

let score=0
let blue ='blue',red = 'red'
let currentPlayer = red



const cells = [] // to keep all cell to iterate over them


  for(let i=0;i<9;i++){
    const divCell = document.createElement('div')
    divCell.setAttribute('class', 'cell')
    divCell.setAttribute('id', i)
    gridWrapper.appendChild(divCell)
    cells.push(divCell)

}


cells.forEach( cell => {
    cell.addEventListener('click', (e)=> {
       let id = e.currentTarget.id
        if(!cells.id && currentPlayer === red){
            cells[id] = currentPlayer
            e.target.classList.add('red') 
            currentPlayer = blue
            console.log(currentPlayer);
         } 
        if(!cells.id && currentPlayer === blue){
            cells[id] = currentPlayer
            e.target.classList.add('blue') 
            currentPlayer = red
            console.log(currentPlayer);

        }
       
    })
})```
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think you have a logical error with the cells array check see in pic suppose to be cells[id] and not cells.id

enter image description here

about 4 years ago · Juan Pablo Isaza Report

0

On each click, both if blocks are being invoked. Because changes made in the first if block are satisfying the second condition. Make the second if an else if:

if (!cells.id && currentPlayer === red) {
  //...
} else if (!cells.id && currentPlayer === blue) {
  //...
}

That way each click only invokes one player's turn rather than both.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!