Showing random divs using Jquery

I find sorting them randomly then showing the first 4 to be the easiest, like this:

var divs = $("div.Image").get().sort(function(){ 
            return Math.round(Math.random())-0.5; //so we get the right +/- combo
           }).slice(0,4);
$(divs).show();

You can test it out here. If you want to also randomize the order (not just which are shown), you already have them sorted so just append them to the same parent in their new order by changing this:

$(divs).show();
//to this:
$(divs).appendTo(divs[0].parentNode).show();

You can test that version here.

Leave a Comment