views:

28

answers:

1

Hey,

I'm trying to make this simple image rotator but, as usual, my code doesn't work. I want to swap between 2 images ("image1" and "image2")

$x = 0;
function rotateImage(){
    if($x == 0){  //if function is being called for the first time
        $x = 1;
    }
    $(".window").html("<img src=\"../images/image" + $x + ".png\" />");
    $x = $x + 1;
    if($x > 2)  
        $x = 1;  //reset x to 1 if last image has been reached
}

rotateImage();  //first function call
setInterval("rotateImage()", 1000);  //call function every second

Image1 shows up but there is no swapping going on.

Thanks in advance,

Matt

+2  A: 

You don't need dollar signs in javascript for variables, and x as an integer doesn't add well with strings. Try this and let me know if you have any issues:

var x = '0'; 
function rotateImage(){ 
    if (x == '0') { x = '1'; } else { x = '0'; }
    $(".window").html("<img src=\"../images/image" + x + ".png\" />"); 
} 

rotateImage();  //first function call 
setInterval("rotateImage()", 1000);  //call function every second 

Also.. are you sure that ".window" is the proper selector to use for the image container? I recommend having the image in a DIV with an ID and using "#theID" as a selector.

Fosco
Hmm, it doesn't seem to work. In response to your other question, I have a div with class "window" (which, come to think of it, is a rather poor name).
Matt
Where are the last two lines of code being executed? Is it in the document.ready/onload function?
Fosco
Yes, all of the above code is in the document.ready function.
Matt
Try taking the function out, having it by itself.
Fosco
Tried that too...I think I'm just going to get a plug-in. Thanks for your help.
Matt
Can you provide more of an example, or a public URL? It's most likely that you're making a very small mistake.
Fosco
Div: <div class="window"> </div>javascript: var x = "1"; function rotateImage(){ if (x == "1") { x = "2"; } else { x = "1"; } $(".window").html("<img src=\"../images/image" + x + ".png\" />"); } rotateImage(); //first function call setInterval("rotateImage()", 1000); //call function every secondThis is exactly as it appears in my files
Matt
sorry, i can't have extra spaces and linebreaks so that's why it looks cluttered
Matt
I don't see why that wouldn't work, but I still suspect some other issue. just for troubleshooting, replace setInterval with setTimeout. if that doesn't work, open FireBug and run rotateImage(); from the console. if that doesn't work, then the issue is completely unrelated.
Fosco