Timothy Coetzee Timothy Coetzee - 1 year ago 70
Javascript Question

How do I cycle through a set of images?

I'm trying to make a banner that cycles through 3 images using JavaScript.

Each image should be displayed for 10 seconds before changing.

I wrote some code but it is not working. It stays stuck on the first image. The Image does not change as I want it to.

Can you see anything in the code and point out my mistakes?

Code as follows:

<script type="text/javascript">
function changeBanner(){
var img = new array

img[0] = document.images[0].src
img[1] = document.images[1].src
img[2] = document.images[2].src

var currentimg = img[0]

if(currentimg == img[0]) {
currentimg = img[1]

if(currentimg == img[1]) {
currentimg = img[2]

HTML as follows:

<body onload="var start=setInterval('changeBanner()', 10000;">
<div id="wrapper">
<img src="budda.JPG" width="900px" height="300px" />

Answer Source
var index = 0;

function changeBanner() {
    [].forEach.call(document.images, function(v, i) {
        document.images[i].hidden = i !== index
    index = (index + 1) % document.images.length;
window.onload = function() {
    setInterval(changeBanner, 1000)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download