A plugin function as such will allow you to do what you want:
jQuery.fn.rotateClasses = function(classes, interval, max) {
var currentRotation = 0;
var timer = null;
var rotateFn = (function() {
var currentClass = currentRotation % classes.length;
var previousClass = currentClass - 1;
if(previousClass == -1) previousClass = classes.length - 1;
this.addClass(classes[currentClass]).removeClass(classes[previousClass]);
currentRotation += 1;
if(max > 0 && currentRotation >= max) clearInterval(timer);
})();
timer = setInterval(rotateFn, interval);
return this;
};
Then you can simply call it using the following:
$('#mydiv').rotateClasses(["class1", "class2", "class3"], 1000, 20);
Simply modify the parameters as you wish. First parameter is an array of classes to rotate, second is the interval to rotate them to, and the third is the maximum number of iterations. If set to 0
, it iterates ad-infinitum.