There are several functional issues in your code:
- The code in the onload attribute of the body tag was not closed correctly
- The code inside changeBanner will always execute all if statements, never progressing with the image loop
Regardless of the corrections, you can make the code a little cleaner, remove the built-in scripts from the body tag and fix the if problem by specifying an index to track the current image in the set.
Assuming you have HTML similar to yours, with three images starting with hidden :
<body> <div id="wrapper"> <div> <img src="http://placehold.it/100x150" width="300px" height="150px" hidden /> <img src="http://placehold.it/200x250" width="300px" height="150px" hidden /> <img src="http://placehold.it/300x350" width="300px" height="150px" hidden /> </div> </div> </body>
You do not need to use the onload attribute for body .
Using window.onload , you can assign a function that will be called automatically after the load event, which, after the DOM completes and all images are loaded.
It is advisable that all your script code be contained in a separate .js file and include only a link to it in your HTML. However, I just supported your current approach for simplicity.
Inside this function, you can configure your variables and then run an interval similar to this:
<script type="text/javascript"> var currentImageIndex = -1, maxImageIndex = 0, images = [], changeInterval = 1500; </script>
DEMO - Fix logical problems and use windows.onload()
source share