0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

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).
Where are the last two lines of code being executed? Is it in the document.ready/onload function?
Yes, all of the above code is in the document.ready function.
Try taking the function out, having it by itself.
Tried that too...I think I'm just going to get a plug-in. Thanks for your help.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.