jQuery: shuffle elements

jQuery doesn't provide a method for shuffling elements, so I've created a global $.shuffle() utility function that returns one or more random elements from a DOM collection. This function is very simple but in my humble opinion it should be enhanced much more, for example by making it return always more than one element. It is as follows:

(function($) {


  $.shuffle = function(element) {
  
    element = $(element);
    var domElem = element[0];
    var shuffled = [];
    var nodes = domElem.childNodes;
    var len = nodes.length;
    
    
    
    
    
      for(var i = 0; i < len; i += 1) { 
      
        if(nodes[i].nodeType == 1) {
      
      
          var node = nodes[Math.floor(Math.random() * len + 1)];
        
          shuffled.push(node);
        
        
        
        }
      
      
      
      
      }
    
    
    
    
    return shuffled;
    
    
  
  
  
 };
 
})(jQuery); 

A simple test:

$('#run').click(function(e) {
  
  
    var shuffled = $.shuffle('#test');
    
    $.each(shuffled, function(index, value) {
    
    
      var elem = $(value).clone();
      
      
      elem.appendTo('#target');
    
    
    });
    
    
    e.preventDefault();
  
  
  
});

You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.