Luis Alvarado
Luis Alvarado

Reputation: 9406

Changing between multiple classes with jquery

I have the following code:

<div class="drawing1"></div>    
<button id="start">Begin</button>

When the user clicks on the Button, the class assigned to the DIV element should change from drawing1 to drawing5, passing through each drawing in between (There are 5 drawings in total). It should also have a delay() of about 500. My first thought was:

$('div').delay(800).toggleClass('drawing1 drawing2');

Which works but when I try to add the rest of the drawings (Tried several methods using toggleclass and add/remove class), it either jumps to the last one or only does the second one.

How can I set this up so I can go from one drawing class to the next, going through each one, one by one with the delay applied for each.

Upvotes: 1

Views: 132

Answers (2)

rdp
rdp

Reputation: 2745

var i = 2; //Assumes drawing1 is already applied to the div
var nextDrawing = function(){
    $("div").removeClass()
            .addClass("drawing"+i);

    i = ((i + 1) % 5); //To cycle from 1 to 5
    i = i == 0 ? 5 : i;
}
$('#start').click(function(){
    setInterval(nextDrawing, 500);
});

Should do the trick.

Edit: The following modification may be useful to someone for clearing the interval if someone clicks the button more than once.

var i = 2; //Assumes drawing1 is already applied to the div
var nextDrawing = function(){
    $("div").removeClass()
            .addClass("drawing"+i);

    i = ((i + 1) % 5); //To cycle from 1 to 5
    i = i == 0 ? 5 : i;
}

var intervalID = undefined;
$('#start').click(function(){
    if( intervalID != undefined )
    {
        clearInterval(intervalID);
    }
    intervalID = setInterval(nextDrawing, 500);
});

Here is a working example: http://jsfiddle.net/ajhuU/

Upvotes: 3

Matyas
Matyas

Reputation: 13712

var leMethod = function(){ // wrapping in a method localizes variables
  var max = 5;             // nr of drawings
  var activeIdx = 0;       // active drawing
  var timeout = 500;       // the time between changes
  var originalClass = 'some classes that are always there';

  setTimeout(function(){               // execute the method on timeout expiration
    var el = $('div');                 // get whatever element you wish to manage
    el.attr('class', originalClass);   // restore original class
    el.addClass('classNr'+activeIdx);  // add your cycle class
    activeIdx = (activeIdx+1) % max;   // update index
  }, timeout);
};

leMethod();

Upvotes: 0

Related Questions