-1

In this code when I use [i] it does not work but if I use [0] or [1] instead of [i] it works. I do not understand why [i] is not working with src.

HTML code


    <div  class="player">
     <p >Player 1
     </p>
     <img  id="myimg" src="images/dice6.png">

    </div>
    
    <div class="player">
        <p> Player 2
        </p>
        <img  id="myimg" src="images/dice6.png">
   
    </div>

JS code

var images = ["images/dice1.png","images/dice2.png","images/dice3.png","images/dice4.png","images/dice5.png","images/dice6.png"];


for (var i = 0; i < document.querySelectorAll("#myimg").length; i++){
document.querySelectorAll("#myimg")[i].addEventListener("click", changeImg);

 function changeImg(){
 var randomNumber1 = Math.floor(Math.random() * images.length);

 document.querySelectorAll("#myimg")[i].src = images[randomNumber1] ;
 }
}

1 Answers1

0

Don't use ID's double they had to be unique. Better use classes instead.

Edited Version

In the eventListener call a function for your changeImg. There get the random Image and use `this`to get the actual element and change the source.

Note: Because random in JS is not really random I added to search as long random as the image is the same like actual. Otherwise you had sometimes to click multiple for a change.

For testing it's better to see if you use the full_page link (in the upper right corner of the output window).

var images = ["https://media.flaticon.com/dist/min/img/home/kiranshastry.png","https://www.pokewiki.de/images/thumb/d/d5/Sugimori_848.png/250px-Sugimori_848.png","https://assets.pokemon.com/assets/cms2/img/pokedex/full/034.png","https://assets.pokemon.com/assets/cms2/img/pokedex/full/030.png"];

for (let i = 0; i < document.querySelectorAll(".myimg").length; i++){
  document.querySelectorAll(".myimg")[i].addEventListener("click", changeImg);
}

function changeImg(){
  let randomNumber1;
  do {
      randomNumber1 = Math.floor(Math.random() * images.length);
  } while (this.src == images[randomNumber1]);
  this.src = images[randomNumber1] ;
}
<div  class="player">
     <p >Player 1</p>
     <img  class="myimg" src="https://www.pokewiki.de/images/thumb/d/d5/Sugimori_848.png/250px-Sugimori_848.png">
</div>
 <div class="player">
     <p> Player 2</p>
     <img  class="myimg" src="https://assets.pokemon.com/assets/cms2/img/pokedex/full/034.png">
</div>
Sascha
  • 4,576
  • 3
  • 13
  • 34