Skip to content
Advertisement

how to prevent the innerHTML of change again after the click event [closed]

let player1 = document.getElementById("player1").innerHTML;
let player2 = document.getElementById("player2").innerHTML;

let turn = 0
let blocks = document.getElementsByClassName("blocks");

for (let i of blocks) {
  i.addEventListener("click", (event) => {
    i.innerHTML = turn
    if (turn == 0) {
      event.target.innerHTML = player1
      turn = 1
    } else {
      event.target.innerHTML = player2
      turn = 0
    }
  })
}
<div class="container">

  <div>
    <div id="0" class="blocks"></div>
    <div id="1" class="blocks"></div>
    <div id="2" class="blocks"></div>
  </div>

  <div>
    <div id="3" class="blocks"></div>
    <div id="4" class="blocks"></div>
    <div id="5" class="blocks"></div>
  </div>

  <div>
    <div id="6" class="blocks"></div>
    <div id="7" class="blocks"></div>
    <div id="8" class="blocks"></div>
  </div>

</div>

<div id="player1" class="players">๐Ÿ‘ต๐Ÿฟ</div>
<div id="player2" class="players">๐Ÿ‘ต๐Ÿป</div>

Advertisement

Answer

Just test for innerHTML first to see if there is already somethign in there…

if (i.innerHTML.trim() != '') return;

let player1 = document.getElementById("player1").innerHTML;
let player2 = document.getElementById("player2").innerHTML;
let turn = 0
let blocks = document.getElementsByClassName("blocks");
for (let i of blocks){
i.addEventListener("click", (event)=>{
    if (i.innerHTML.trim() != '') return;
    i.innerHTML = turn 

    if (turn == 0){
        event.target.innerHTML = player1
        turn = 1
    }
    else {event.target.innerHTML = player2
    turn = 0}

})
}
.blocks {
padding:20px;
text-align:center;
border:1px solid #666;
float:left;
margin-right:5px;
}
 <div>
        <div id="0" class="blocks"></div>
        <div id="1" class="blocks"></div>
        <div id="2" class="blocks"></div>
    </div>
    
    <div>
        <div id="3" class="blocks"></div>
        <div id="4" class="blocks"></div>
        <div id="5" class="blocks"></div>
    </div>

    <div>
        <div id="6" class="blocks"></div>
        <div id="7" class="blocks"></div>
        <div id="8" class="blocks"></div>
    </div>

</div>

<div id="player1" class="players">๐Ÿ‘ต๐Ÿฟ</div>
<div id="player2" class="players">๐Ÿ‘ต๐Ÿป</div>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement