A jQuery plugin to add a random class from a selection of classes to an element. Use it creatively. ;-)
Demo Usage Styling Download Compatibility Changelog
In this demo we're adding random classes to some words with the default settings. Each word is inside a span, so we can easely target them:
This is just some random text to show some random classes applied to words in a sentence that is not actually ment to be read .
var c = [ 'color1','color2','color3','color4','color5' ];
$("p.demo.defaults span").randomClass( c );
The same text with the same default settings:
This is just some random text to show some random classes applied to words in a sentence that is not actually ment to be read .
As you can see, it really is random. But what if we don't want to apply the same class to successive elements? No problem, we have an option for that:
This is just some random text to show some random classes applied to words in a sentence that is not actually ment to be read .
$("p.demo.successive span").randomClass( c, { randomness: 'successive' } );
Now sometimes you may want even less randomness, you basically want a random pattern to repeat itself, and yes, there's an option for that:
This is just some random text to show some random classes applied to words in a sentence that is not actually ment to be read .
$("p.demo.pattern span").randomClass( c, { randomness: 'pattern' } );
You can remove previously added classes with the 'removeClasses' option: Test
$('p.demo.pattern span').randomClass(
[ 'color1','color2','color3','color4','color5' ],
{ randomness: 'pattern', removeClasses: true }
);
This is how you use the plugin with default options:
$("p span").randomClass( [ 'classname1', 'classname2', 'classname3' ] );
And with options (in this example, they are exactly as the defaults):
$("p span").randomClass(
[ 'classname1', 'classname2', 'classname3' ],
{
randomness: 'default',
removeClasses: false
}
);
Options for randomness are: 'default', 'successive' and 'pattern'
The removeClasses option is there so you can remove previously added classes (those that are in the classes array)
Here's how the demo was styled (nothing special):
p.demo {
line-height: 200%;
letter-spacing: 1px;
}
p.demo span {
color: #fff;
padding: 2px;
padding-right: 4px;
padding-left: 4px;
}
.color1 {
background: #774356;
}
.color2 {
background: #E39358;
}
.color3 {
background: #A00139;
}
.color4 {
background: #530A53;
}
.color5 {
background: #0289A1;
}
Current version: jquery.randomclass-0.2.js (1.3k not minified)
Tested in:
There really is nothing complicated in there, so expect the plugin to work in older browsers as well.