2

I'm trying to shuffle the order of a jQuery selection without shuffle the elements in the DOM.

I need to shuffle the selection to add a class to each element in random order, this is how my code should look:

$(".item").shuffle().each(function (i, element) {
    $(element).delay(i * 100).queue(function (next) {
        $(this).addClass("shown");
        next();
    });
});

Can someone help me finding the shuffle() function I need?

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160
  • it looks like you are trying to shuffle the order of some list elemets. google search for 'suffle unordered list' http://stackoverflow.com/questions/14555415/jquery-how-to-random-sort-list-items – superUntitled Jul 18 '14 at 18:48

2 Answers2

6

I borrowed the Array.shuffle method from this answer, and made it into a jQuery plugin

$.fn.shuffle = function(){
    for(var j, x, i = this.length; i; j = Math.floor(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
    return this;
};

FIDDLE

Community
  • 1
  • 1
adeneo
  • 312,895
  • 29
  • 395
  • 388
0
$.fn.shuffle = function () {
    'use strict';
    var self = this,
        i,
        rnd,
        len = self.length - 1;
    for (i = len; i > 0; i -= 1) {
        rnd = Math.floor(Math.random() * len) % i;
        [self[i], self[rnd]] = [self[rnd], self[i]];
    }
    return self;
}
Ivan Ivanov
  • 2,076
  • 16
  • 33