I have the following little script that seems to work but two of the images appear broken. They load when I right click and load as new tab:
var target = document.getElementById('target');
var counter = 0;
var myPictures = [
'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif',
'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif',
'https://media.giphy.com/media/1nkUav308CBws/giphy.gif'
];
function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="https://media.giphy.com/media/1nkUav308CBws/giphy.gif" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />
</body>
</html>
Just move this line inside your
nextPic()
function so you don't try to grab thatdiv
before it gets loaded in the DOM.Sometimes
<script defer>
will automagically wait for the DOM to load, sometimes it doesn't. It's JavaScript. It is what it is.Here's a good backstory on script loading.