Blog of an Interactive Storyteller

View Original

Random-Sort jQuery Plugin

About the “randomsort” Plugin

A simple yet handy jQuery plugin to randomize the contents of a container. Simply include jQuery and the randomsort scripts in your page and choose one of the approaches below to randomly sort containers of your choosing.

How it Came About

I heard that the Kids Read Comics organizers wanted to randomize the display of their event’s Guests list of profiles. Showing the list sorted different on every page visit would make the list feel less like a marquee of most to least popular people.

After a little bit of experimenting (quick prototype, then integrating/testing with their Wordpress-based Guests page) it worked as planned and a handy code snippet was born.

I thought it’d be fun to make a jQuery plugin out of that snippet!

Using the Plugin

First, include jQuery and the randomsort.js scripts. Then give a container within your HTML a class of “randomsort”,“randomsortchildren”, or “randomsortsiblings”.

Demo

Code

(function( $ ){
        var methods = {
            sortchildren : function( options ) {
                return $(options).each(function(){
                    var divs = $(options).children().sort(
                    function(){
                        return Math.round(Math.random())-0.5;
                    }); 
                    divs.appendTo(divs[1].parentNode).show();
                });
            },
            sortsiblings : function( options ) {
                return $(options).each(function(){
                    var divs = $(options).siblings().sort(
                    function(){
                        return Math.round(Math.random())-0.5;
                    }); 
                    divs.appendTo(divs[1].parentNode).show();
                });
            }
        };
        $.fn.randomsort = function( method ) {
            if ( methods[method] ) {
                return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
            } else if ( typeof method === 'object' || ! method ) {
                return methods.init.apply( this, arguments );
            } else {
                $.error( 'Method ' +  method + ' does not exist on jQuery.randomsort' );
            }
        };    
        jQuery(window).ready(function() {
            $("#randomsort,.randomsort").each(function(){
                $(this).randomsort("sortchildren", $(this));
            });            $("#randomsortchildren,.randomsortchildren").each(function(){
                $(this).randomsort("sortchildren", $(this));
            });            $("#randomsortsiblings,.randomsortsiblings").each(function(){
                $(this).randomsort("sortsiblings", $(this));
            });    
        });
    })( jQuery );

Grab the source and demo file at BitBucket.