devMeSilus
devMeSilus

Reputation: 21

JavaScript Timed Image Swap Need Help

So in my script I have...

<script type="text/javascript">
var images = new Array();
var numImages = 3;
var index = 0;

function setupSwapper() {
    for (i = 0; i < numImages; i++) {
        images[i] = new Image(266, 217);
        images[i].src = "images/image" + i + ".png";
    }
    setTimeout("swapImage()", 5000);
}

function swapImage() {
    if (index >= numImages) {
        index = 0;
    }
    document.getElementById('myImage').src = images[index].src
    index++;
    setTimeout("swapImage()", 5000);
}
</script>

And then I have <body onload="setupSwapper()"> to setup the body.

and <img width=266 height=217 id="myImage" name="myImage" src="images/image0.png"></img> elsewhere in my document.

Only the initial image (image0.png) is showing up. I'm probably blind from having looked at this so long. The images are not swapping.

Upvotes: 0

Views: 782

Answers (4)

letronje
letronje

Reputation: 9148

Get Firebug, use it's debugger to put breakpoints inside swapImage to see if it is hit after the timeout. Another way is to use the console.* apis to see what's happening(e.g. console.log).

Upvotes: 0

gblazex
gblazex

Reputation: 50109

The way to go:

  1. setTimeout(swapImage, 5000);
  2. [FORGET] the type attribute has nothing to do with it
  3. [FORGET] the index has nothing to do with it
  4. [OPTIONAL] remove "name" attribute from the image (useless)
  5. [OPTIONAL] close image tags like <img />

Note: 2-5 is about correctness. Only the first one is important to get it work.

Upvotes: 0

ob1
ob1

Reputation: 1721

Use FireBug or a similar tool for debugging what's going on:

  • Does the img DOM element in fact gets its src changed ?
  • Do you see any network activity trying to load the images ? does it succeed ?
  • Set up breakpoints in your code and see what happens in the debugger

BTW - You can use setInterval instead of setTimeout - it sets a repeating timer

Upvotes: 1

Pointy
Pointy

Reputation: 413717

You're missing the () in the definition of "setupSwapper".

Also it's setTimeout, not setTimeOut.

Finally, get rid of the "type" attribute on your <script> tag.

You might want to start "index" at 1 instead of 0.

Upvotes: 0

Related Questions