javascript - Adding an Image to HTML Based on Outcome of If/Else (innerHTML? DOM?) -
i'm doing basic rock paper scissors game in javascript, nothing new i'm trying fancy little. of ones see output computer selected in plain text via innerhtml , that's fine want show image based on selected.
the basic game function playgame passes choice comparechoices function. instead of passing "the computer chose: rock" span id="result" pass image. i've been reading dom , nodes , stuff i'm having difficulty understanding how apply here.
let's assume have image named rock.gif want pass result span when computer selects "rock". how do it? if involves using dom , not innerhtml please me understand , explain little 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 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>
ok, slimmed down code needed.
basically put empty image tag on page , set src javascript. take looks , let me know if there dont understand. have right click , inspect image see src, until have th eimages in 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>
Comments
Post a Comment