0

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?

dubbs
  • 1,167
  • 2
  • 13
  • 34
  • Can you create a fiddle? – Purus Dec 06 '13 at 12:02
  • 1
    Look into [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval), `setTimeout` etc for the delay and [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) for choosing the element, it's pretty self-explanatory from there. – Mike Campbell Dec 06 '13 at 12:04

2 Answers2

3

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
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

Community
  • 1
  • 1
Purus
  • 5,701
  • 9
  • 50
  • 89