bnr32jason bnr32jason - 1 month ago 11
Javascript Question

Adding an Image to HTML Based on Outcome of If/Else (innerHTML? DOM?)

I'm doing a basic rock paper scissors game in Javascript, nothing new but I'm trying to fancy it up a little. All of the ones I see just output what the computer selected in plain text via innerHTML and that's fine but I want it to show an image based on what they selected.

The basic game function playGame passes the choice into a compareChoices function. Instead of passing "The computer chose: rock" into my span id="result" I would like to pass an image. I've been reading about DOM and nodes and stuff but I'm having difficulty understanding how to apply it here.

Let's assume I have an image named rock.gif that I want to pass to the result span when the computer selects "rock". How do I do it? If it involves using DOM and not innerHTML please help me to understand and explain a little what is going on. Thanks!

function playGame(userSelect)
{

userOption = userSelect;

var computerSelection = Math.random();

if (computerSelection < 0.34)
{
computerSelection = "rock";

}
else if (computerSelection <= 0.67)
{
computerSelection = "paper";
}
else
{
computerSelction = "scissors";
}

results = compareChoices(userOption, computerSelection);

document.getElementById("result").innerHTML = "<p>The computer chose " +
computerSelection;
document.getElementById("whoWon").innerHTML = results;
}


function compareChoices(userOption, computerSelection)
{


if (userOption == computerSelection)
{
return "It's a tie!";
}

if (userOption == "rock")
{
if (computerSelection == "scissors")
{
return "You win!";
}
else
{
return "You lose!";
}

} else if (userOption == "paper") {

if (computerSelection == "rock")
{
return "You win!" ;
} else if("scissors") {
return "You lose!" ;
}

} else if (userOption == "scissors") {

if (computerSelection == "rock")
{
return "You lose!";
}else{
return "You win!";
}
}
}


HTML

<span id="result"></span>

Answer

Ok, so I slimmed down your code to only what I needed.

Basically put an empty image tag on the page and then set the src with the javascript. Take a looks and let me know if there is anything you dont understand. You will have to right click and inspect the image to see the src, until you have th eimages in your project.

user = 0.64;

playGame(user);

function playGame(userSelect) {

  userOption = userSelect;

  var computerSelection = Math.random();

  if (computerSelection < 0.34) {
    computerSelection = "rock.gif";

  } else if (computerSelection <= 0.67) {
    computerSelection = "paper.gif";
    
  } else {
    computerSelection = "scissors.gif";
  }

  

  document.getElementById("result").innerHTML = "<p>The computer chose " +
    computerSelection;
  document.getElementById("image").src = computerSelection;
}
<img id="image" src="">
<span id="result"></span>
<span id="whoWon"></span>