I'm just learning some java. I am currently learning if, else statements.
In the game I am creating, the user picks a number between 0 and 10 and puts it into an input box. If correct, the image on screen changes to one picture, if incorrect, it switches to a different picture. However, I cannot seem to get the images to change at all. I've tried a few different ways of coding; I'm currently using an img array. However, when I do the code I receive an ObjectHTMLImageElement error.
Here is my current code:
<div id="top">
<h1>Pie in the Face</h1>
<p>Guess how many fingers I'm holding up between 0 and 10.
<br /> If you guess correctly, I get a pie in the face.
<br /> If you guess wrong, you get a pie in the face.</p>
<input id="answer" />
<button id="myButton">Submit</button>
</center>
</div>
<div id="container">
<div id="image"></div>
<div id="manpie"></div>
<div id="girlpie"></div>
</div>
<script type="text/javascript">
var x = Math.random();
x = 11 * x;
x = Math.floor(x);
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "images/manpie2.jpg";
imgArray[1] = new Image();
imgArray[1].src = "images/girlpie2.jpg";
document.getElementById("myButton").onclick = function() {
if (x == document.getElementById("answer").value) {
document.getElementById("image").innerHTML = imgArray[0];
// what I had document.getElementById("image").innerHTML=imgArray[0];
} else {
document.getElementById("image").innerHTML = imgArray[1];
}
}
</script>
</body>
I have also tried using lines such as: document.getElementById("image").innerHTML=document.getElementById("manpie");
and then nothing works. Here is a link to the "live" site it's on. http://176.32.230.6/mejorarcr.com/
any help would be appreciated. Thank You!
You have to change the innerHTML
value in your code:
if (x==document.getElementById("answer").value) {
document.getElementById("image").innerHTML='<img src="'+imgArray[0].src+'" />';
// what I had document.getElementById("image").innerHTML=imgArray[0].src;
} else {
document.getElementById("image").innerHTML='<img src="'+imgArray[1].src+'" />';
}
DEMO or this
change:
document.getElementById("image").innerHTML=imgArray[0];
to:
document.getElementById("image").setAttribute("src", imgArray[0]);
make sure imgArray[0] is the actual image path:
imgArray[0]="images/manpie2.jpg";
imgArray[1]="images/girlpie2.jpg";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With