0

I'm trying to make my DIV background loop between 3 images. I have a DIV and 3 classes, each specifying unique backgrounds.

On page load, I need javascript to append .class1 to the DIV, then half a second later, remove class1 and add .class2; again half a second later, remove class2 and add .class3; finally, remove class3 and go back to the first class and start again.

HTML:

<div id="rabbit"></div>

CSS:

.rabbit1 {background: url(http://i.imgur.com/fd3fo.jpg);}
.rabbit2 {background: url(http://i.imgur.com/SHknQ.jpg);}
.rabbit3 {background: url(http://i.imgur.com/Utel1.jpg);}

Here is the jsfiddle: http://jsfiddle.net/XDUSA/

I'm sorry, I'm new to this and I don't know where to start. Thank you for your help in advance.

izolate
  • 1,590
  • 4
  • 22
  • 35

3 Answers3

8

Try this:

var i = 0; // Declare a global variable to hold the current iteration value.
function changeClass(){
    $("#rabbit").removeClass("rabbit" + i)
        i = (i==3)?1:i+1;    
    $("#rabbit").addClass("rabbit" + i);

}
setInterval(changeClass, 500);

Working example: http://jsfiddle.net/XDUSA/1/

i = (i==3)?1:i+1; can be written as:

if(i == 3){ 
   // If the code reached this point the class assigned to the element in last iteration is rabbit3
   i=1; //Reset to 1
} else{ // More room to increment i
  i = i+1;
}
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • Works perfectly! Thanks. Do you mind explaining what `i = (i==3)?1:i+1;` does? I understand everything else but this part. I get what it's supposed to do, but I can't comprehend how you achieved it. – izolate Jul 27 '11 at 03:01
1

what your looking for is the addclass() and removeclass() functions http://api.jquery.com/addClass/ and http://api.jquery.com/removeClass/ on a timer http://www.w3schools.com/js/js_timing.asp

a good read for doing this is Loop timer in javascript

Community
  • 1
  • 1
webLacky3rdClass
  • 659
  • 10
  • 27
1

Cybernate has the best solution, but if you ever need to implement a toggle function, you can always use .toggle(): http://jsfiddle.net/rkw79/XDUSA/4/

$('div').click().toggle(
    function() {$(this).attr('class','rabbit2')},
    function() {$(this).attr('class','rabbit3')},
    function() {$(this).attr('class','rabbit1')}
)
rkw
  • 7,287
  • 4
  • 26
  • 39