Reputation: 1199
I am looking to find a way in jQuery to randomly add a class to a range of DIVs over a period of time until they all have had the new class added to them.
$(document).ready(function(){
$(".cardWrapper > div").addClass('flip');
});
This works to add the class 'flip' to the DIVs inside the .cardWrapper DIV, but what I need is for the addclass action to happen one at a time and ideally in a random fashion - so basically, each of the 10 DIVs gets the 'flip' class added to it in a random sequence with a definable delay inbetween each addclass being added...
Is this possible?
Upvotes: 0
Views: 1796
Reputation: 5799
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
Given the shuffle, you can then pick X elements at random with
var items = shuffle($(".cardWrapper")).slice(0, X);
Then you can apply your class for the item.
This is how I did for my requirement. The logic is from jQuery select random elements with same class
Upvotes: 0
Reputation: 388316
Try
$(document).ready(function () {
var $divs = $(".cardWrapper > div");
var interval = setInterval(function () {
var $ds = $divs.not(".flip");
$ds.eq(Math.floor(Math.random() * $ds.length)).addClass('flip');
if ($ds.length == 1) {
clearInterval(interval);
}
}, 500);
});
Demo: Fiddle
Upvotes: 3