Reputation: 1
So I'm new to coding, so thought that I would give some more simple things a go. I tried to make a code which would change an image every time a button is pressed, but it does not function. For a while I had it functioning so that the square would display but the image would not change when the button is pressed. But I then altered it and it will now not run with internet explorer due to a syntax error. Any help would be seriously appreciated, please bare in mind that it could be completely wrong, as I just used guides off of the internet :) I also probably inserted this code wrong, but I tried ;)
<!DOCTYPE html>
<html>
<body>
<img id="shape" src="square.gif">
<button type="button" onclick="changeImage()">Change Image/button>
<script>
var list = [
"red.gif",
"square.gif"
];
var index = 0;
function changeImage() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('shape');
image.src=list[index];
}
</script>
Upvotes: 0
Views: 30
Reputation: 3139
I did find two things that will help your code work better:
This tested fine in IE with no errors.
See my code below.
var list = [
"http://placekitten.com.s3.amazonaws.com/homepage-samples/96/140.jpg",
"http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg"
];
var index = 0;
function changeImage() {
var image = document.getElementById('shape');
if (index == list.length) index = 0;
image.src=list[index];
index = index + 1;
}
<img id="shape" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg" />
<button type="button" onclick="changeImage()">Change Image</button>
Upvotes: 4