views:

40

answers:

4

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.

+1  A: 

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

ob1
A: 

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.

Pointy
sorry about that, those are both just typos unfortunately, i wish it was that easy. i'll edit that in.
devMeSilus
I've updated the answer again.
Pointy
A: 

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.

galambalazs
Pointy: (why did you remove your comment?) Hm, maybe you could point to an example, or relating part in Firefox source code, because it's just plain stupid. Type attribute is part of the HTML4 specification, although it is ignored (the attribute not the content) by most browsers. The reason is that they are trusting the content-type header more than the script's type attribute. This is why they took it out from HTML5 spec. But it will cause no errors, and is valid (X)HTML!
galambalazs
I removed my comment because it was wrong :-)
Pointy
happens to everyone... :)
galambalazs
setTimeout("swapImage()") should work too.
letronje
A: 

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).

letronje