Yelotofu

Yelotofu ~ “In building standards compliant sites we are creating a better Web for the future.”

jQuery: Shuffle Plugin

Tags: , , , ,

I recently came across a really compact array shuffling function on JSFromHell.com, which I thought would make a nifty jQuery plugin.

This jQuery shuffle plugin could be applied to any HTML element or Array object.

 
(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
})(jQuery);
 

Due to line wrapping issues in this post I inserted a few hard carriage returns in the above snippet (sorry).

Example 1: shuffle an unordered list

 
$('ul').shuffle();
 

Example 2: shuffle an array

 
var arr = [1,2,3,4,5,6];
arr = $.shuffle(arr);
 

There is a demo here. And for those interested I encourage you to download the plugin for closer inspection.

Similar Posts

12 Comments

  1. By Raphael Martins at

    Nice work! =)

  2. By Mike B. at

    Very nice script – thank you!

  3. By Elle at

    Nice script. Could I ask for your help on how to alter the script so it shuffles through an array but only shows just one array item — which would change on page reload?

  4. By caphun at

    @Elle: Thanks. Yes that’s certainly possible. Try this:

    jQuery(function($){
    var randomItem = $.shuffle([1,2,3,4,5,6])[0];
    alert(randomItem);
    });

    The above will return a random number between 1 and 6.

  5. By Shuffling the DOM - James Padolsey at

    [...] was recently looking for a decent way of shuffling a set of elements. I found a jQuery plugin which claimed to do exactly that but unfortunately it only works if all elements are direct [...]

  6. By Implement Array Shuffling in MooTools at

    [...] useful function, I recently found myself needing to accomplish the task. I found a great post about how to achieve this feat using jQuery.  Here’s how to implement array shuffling in [...]

  7. By Rustam Mester at

    Big thanks to author from russian freelancer !

  8. By Manish MISTRY at

    Thanks mate!

  9. By Hector Virgen at

    Very nice! Just what I was looking for and it seems quick.

    But I ran into a small problem — all event bindings will be lost after shuffling. I made a small modification that allows you to keep your bindings by using clone(true):

    $.fn.shuffle = function()
    {
    return this.each(function()
    {
    var items = $(this).children().clone(true);
    return (items.length)
    ? $(this).html($.shuffle(items))
    : this);
    });
    };

  10. By caphun at

    @hector – makes sense to keep the bindings! I will add that into my code aswell. Thanks!

  11. By Ellison at

    Hello. I’ve made an attempt at extending this plugin a little to be able to seed a random number generator so that you can repeat sequences given the right seed. I’m very new at jQuery, so if I didn’t do something quite right (style-wise or other), please tell me :)

    (function($){
    var getNextRandom = Math.random;
    $.fn.shuffle = function() {
    return this.each(function(){
    var items = $(this).children().clone(true);
    return (items.length) ? $(this).html($.shuffle(items)) : this;
    });
    }

    $.shuffleInit = function(options) {
    if(!options || !Random) return;
    if(typeof options.seed == “number”) {
    var r = new Random(options.seed);
    getNextRandom = function() { return r.next(); };
    }
    }

    $.shuffle = function(arr) {
    for(var j, x, i = arr.length; i; j = parseInt(getNextRandom() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
    }

    })(jQuery);

    It seems to work fine, assuming that you’ve loaded a class called Random that works appropriately (i.e. a 1-arg constructor to initialize the seed and a next() method to get the next pseudo-random number).

    Again, I’d much appreciate tips on how I can improve what I was trying to do.

  12. By bamboolabcode at

    Thanks for the info. I appreciate it well.

Leave a Reply

* marks a required field.



(this will not be published)