so i'm new coding, thought give more simple things go. tried make code change image every time button pressed, not function. while had functioning square display image not change when button pressed. altered , not run internet explorer due syntax error. appreciated, please bare in mind wrong, used guides off of internet :) inserted code wrong, 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>
i did find 2 things code work better:
- i fixed closing button tag
- i iterated index variable after if statement , image replacement. way first click didn't use same image.
this tested fine in ie no errors.
see 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>