Im creating a rock, paper,scissors project but using the water, fire and grass Pokemon instead of traditional Rock Paper Scissors. When I'm clicking the Pokemon of choice "choice" I want the player "player-pokemon" image to switch sources so it can Clearly be shown that it was the choice in the game. However when I try to do this with currentSrc, it won't switch in game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title>Pokemon Battle</title>
</head>
<body>
<div id="container">
<h1 >Pokemon Battle</h1>
<div id="computer-container">
<h2>Gym Leader Score</h2>
<p >0</p>
<img
src="pokeball.jpeg"
id="computer-pokemon"
/>
</div>
<div >
<img src="pokeball.jpeg" id="player-pokemon" />
<p >0</p>
<h2>Trainer Score</h2>
</div>
<div id="choices">
<img src="fire.jpeg" id="fire" />
<img src="water.jpeg" id="water" />
<img src="grass.jpeg" id="grass" />
</div>
</div>
<script src="script.js"></script>
</body>
</html>
const choice = document.querySelectorAll(".choice");
const computerScore = document.querySelector(".computer-score");
const playerScore = document.querySelector(".player-score");
const computerChoice = document.getElementById("computer-pokemon");
let playerChoice = document.getElementById("player-pokemon");
let gymLeaderScore;
let trainerScore;
for (let i = 0; i < choice.length; i ) {
choice[i].addEventListener("click", function () {
// replace player pokeball with chosen pokemon
var playerImg = choice[i].currentSrc;
playerChoice.currentSrc = playerImg;
});
}
I have tried using a loop to collect the choice currentSrc and declare it as a variable playerImg and then make it equal playerChoice.currentSrc variable which is the element for the chose poke ball in img.
CodePudding user response:
Try this
let choicesImg = document.querySelectorAll(".choice");
let imgOfPlayer = document.getElementById("player-pokemon")
choicesImg.forEach(img => {
img.addEventListener('click', e => {
imgOfPlayer.src = e.target.src
})
})
// You can also do it in one line of code like this:
choicesImg.forEach(img => img.onclick = e => imgOfPlayer.src = e.target.src )