i have several divs with the same class. i'd like to randomly add a (different) class to each of these divs, but without having repetitions of the added class right after eachother.
here's my example html:
<div class="sometext"> some text here </div>
<div class="sometext"> some other text here </div>
<div class="sometext"> some more text here </div>
<div class="sometext"> some more text here </div>
<div class="sometext"> some more text here </div>
example css of what should be added:
.addedclass1 {...}
.addedclass2 {...}
.addedclass2 {...}
.addedclass3 {...}
.addedclass4 {...}
what i'd love to see in the end:
<div class="sometext addedclass3"> some text here </div>
<div class="sometext addedclass2"> some other text here </div>
<div class="sometext addedclass4"> some more text here </div>
<div class="sometext addedclass1"> some more text here </div>
<div class="sometext addedclass2"> some more text here </div>
i've got some jquery that randomizes the added class, but it allows repetitions:
$(document).ready(function() {
var classes = ['addedclass1', 'addedclass2', 'addedclass3', 'addedclass4'];
$('.sometext').each(function(i) {
$(this).addClass(
classes[Math.floor(Math.random()*classes.length)]);
});
});
i'd be gracious for any help — i'm a bloody beginner :)
I would create a temporary array each time that contains all the elements from classes except for the previously used class. Then select a random one from that.
JS Fiddle: http://jsfiddle.net/9AbRQ/
This will just get a random index until it is different from the last one used.
This will help you for sure, shot but effective:
jsfiddle: http://jsfiddle.net/ashishanexpert/565ZC/1/
Or, if you want to add the class randomly from an Array, you can do it like this:
jsfiddle: http://jsfiddle.net/ashishanexpert/565ZC/4/
I would just remove the class from the array after you use it, so it can't be used again and the random number will be smaller. If you need the array for something else, just create a copy to do this.