This unique jQuery script, not a typical plugin, is designed to cycle through multiple classes specified as a comma-separated values within the cycler element's data-classes attribute. When toggling between two classes, it operates like a toggle switch. If you start with a class that is not listed, the initial state remains unaltered.
Simply initiate the cycling process with $(selector).cycleClass().
In my case, I utilize a server-side template engine which explains the presence of {{#objModel}} and {{/objModel}} in the code - feel free to remove them if unnecessary for your setup.
This versatile script can be applied to any element that has both class and data-* attributes. The example below includes a button that cycles through different classes on a code block, but the functionality could easily be bound to the button itself for changing its own class.
I initially shared this script as a response to the toggle class question before delving into the concept of cycling classes.
You can witness this script in action 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