Code Snippet

Home » Code Snippets » jQuery » Shuffle DOM Elements

Shuffle DOM Elements

This is from James Padolsey. Check out his article for a pure JavaScript technique as well.

Plugin

(function($){

    $.fn.shuffle = function() {

        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });

        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });

        return $(shuffled);

    };

})(jQuery);

Usage

Target elements, call shuffle.

$('ul#list li').shuffle();

Subscribe to The Thread

  1. Thank you for this post – it’s useful. I’m going to read again jQuery docs about map, get and replaceWith, and about native js splice as well.

  2. Alexandre Cárdenas

    Your web design is awesome. I love it. Congratulations!

    Alex

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~