This jQuery function, not a plugin, will cycle through any number of classes that have been set up as a csv of classes in the cycler element's data-classes attribute. Two classes acts just like a toggle. Start with a class not in the list and the initial state is untouched.
Cycle it with $(selector).cycleClass().
I run mine through a server side template engine, hence the {{#objModel}} and {{/objModel}} remove if you don't.
Works on any element that has class and data-* attributes. The code below has a cycle button to change the class of the code block. But it could have just been on the button itself and changed its own class.
I originally posted this to to answer the toggle class topic/question then found this cycle Class topic.
See it in use at www.PluginExamples.com.
{{#objModel}}
<style>
#cycler.A code {outline:3px solid red;}
#cycler.B code {outline:3px solid blue;}
#cycler.C code {outline:3px dotted green;}
#cycler.D code {outline:3px dotted red;}
#cycler.E code {outline:3px dashed blue;}
#cycler.F code {outline:3px dashed green;}
</style>
<button onclick="$('#cycler').cycleClass();">Cycle</button>
<div id="cycler" data-classes=",A,B,C,D,E,F">
<code
id="cycleClass"
><div id="cycler" data-classes=",A,B,C,D,E,F,">...</div>
<button onclick="$('#cycler').cycleClass();">Cycle</button>
$( ".cycler" ).cycleClass();
$.fn.cycleClass = function(){
if( !$(this).data("aClasses") ){
var classes = $(this).attr("data-classes").split(",");
$(this).data("aClasses", classes);
$(this).data("classes", classes.join(" "));
$(this).data("class", classes.length);
}
$(this).data("class",($(this).data("class")+1) % $(this).data("aClasses").length);
$(this).removeClass($(this).data("classes"))
.addClass( $(this).data("aClasses")[$(this).data("class")] );
return $(this);
}
</code>
</div>
<script>
(function($){
$.fn.cycleClass = function(){
if( !$(this).data("aClasses") ){
var classes = $(this).attr("data-classes").split(",");
$(this).data("aClasses", classes);
$(this).data("classes", classes.join(" "));
$(this).data("class", classes.length);
}
$(this).data("class",($(this).data("class")+1) % $(this).data("aClasses").length);
$(this).removeClass($(this).data("classes"))
.addClass( $(this).data("aClasses")[$(this).data("class")] );
return $(this);
}
});
</script>
{{/objModel}}
[1]: http://www.pluginexamples.com