Element Randomization Demo

Randomize a sequence of divs

HTML

<div id="wrapper">
    <div id="1" class="ran">Div 1</div>
    <div id="2" class="ran">Div 2</div>
    <div id="3" class="ran">Div 3</div>
    <div id="4" class="ran">Div 4</div>
</div>

CSS

#wrapper {
    width:400px;
    margin:0px auto;
    padding:10px;
}
#wrapper > div {
    padding:10px;
    background:#eee;
    border:1px dashed #ccc;
    margin:5px 0;
}

JavaScript

jQuery(function() {
  $("#wrapper").randomize("div.ran");  
});

(function($) {

    $.fn.randomize = function(childElem) {
        return this.each(function() {
            var $this = $(this);
            var elems = $this.children(childElem);

            elems.sort(function() {
                return (Math.round(Math.random()) - 0.5);
            });

            $this.remove(childElem);

            for (var i = 0; i < elems.length; i++)
            $this.append(elems[i]);

        });
    }
})(jQuery);