jquery scramble plugin

an often found way to randomize an array in javascript is the following

[1,2,3,4,5].sort(function() { return 0.5 - Math.random() });

or using a jquery selector

$('.myclass').sort(function() { return 0.5 - Math.random() });

i probably don't have to tell you that this is a bad way to randomize stuff. it also seems to be browser specific and as such some browsers deliver quite good results (based on murphy's law, this will be your test browser) while others almost don't randomize at all.

as i needed the randomization to happen in-place but not touching the elements in the dom at all, i was looking for already existing jquery plugins. unfortunately i was out of luck here. or i didn't search desperately enough. whichever makes you feel better.

i quickly hacked down a jquery plugin which uses the fisher yates shuffle algorithm to shuffle a jquery selection with quite good results.

(function($) {
  $.fn.scramble = function() {
    var len = this.length;
    if (len > 0) {
      var i;
      var tmp;
      while (--len) {
        i = Math.floor(Math.random() * (len + 1));
        tmp = this[i];
        this[i] = this[len];
        this[len] = tmp;
    return this;

you probably want to do something like this afterwards:

var elements = $('.myclass').scramble();

please find the code along with a minified version and demo in the git repository: http://git.dgsiegel.net/jquery-scramble.git

as always, i would be more than happy for any corrections or suggestions!

Want more ideas like this in your inbox?

My letters are about long-lasting, sustainable change that fundamentally amplify our human capabilities and raise our collective intelligence through generations. Would love to have you on board.