jQuery: Randomly reorder children elements of selected elements

categories: front-end development, javascript, jquery, plugins

I'm working on a new template for a client, and they asked me to display some list elements in a random order on each page load. I did my Google due diligence, but didn't come up with anything that wasn't slideshow-like -- what I wanted was just something that would show all of the children elements of an element, but in a random order. (In this particular case, the children elements were case case studies.) I was already using jQuery on the page, so I wrote a plugin:

jquery.reorder.js (1k)

Here's the code:

 
$.fn.reorder = function() {
 
  // random array sort from
  // http://javascript.about.com/library/blsort2.htm
  function randOrd() { return(Math.round(Math.random())-0.5); }
 
  return($(this).each(function() {
    var $this = $(this);
    var $children = $this.children();
    var childCount = $children.length;
 
    if (childCount > 1) {
      $children.remove();
 
      var indices = new Array();
      for (i=0;i<childCount;i++) { indices[indices.length] = i; }
      indices = indices.sort(randOrd);
      $.each(indices,function(j,k) { $this.append($children.eq(k)); });
 
    }
  }));
}
 

Thoughts? Suggestions? Let me know.

3 Responses to “jQuery: Randomly reorder children elements of selected elements”

  1. rdmey | Cycle through list elements with jQuery says:
    January 7th, 2008 at 10:57 pm

    [...] Randomly reorder the list items before you add the rest of the code [...]

  2. Rich Barrett-Small says:
    June 23rd, 2008 at 8:32 am

    This is just what I was looking for. Nicely done, thanks!

  3. Steven Black says:
    September 2nd, 2008 at 6:14 pm

    Hey, thank you very much for that. See it on http://K7Waterfront.org. Works great!

    I found your blog while Googling jQuery terms related to this. Keep up the good work, and thanks for sharing, Rebecca!

    Cheers!

Comment