jquery move elements into a random order

mheavers picture mheavers · Mar 16, 2011 · Viewed 14.4k times · Source

I am attempting to display a series of images in a random order. However, I do not want any single item to repeat until all items have been shown, so instead of selecting a random image from the array, I want to take the entire array, randomize it, and then select in sequence from the first to the last element. Here's my code:

HTML:

<div id="tout4"
<img src="images/gallery01.jpg" class="img_lg"/>
<img src="images/gallery02.jpg" class="img_lg"/>
<img src="images/gallery03.jpg" class="img_lg"/>
</div>

and the javascript, which currently selects and displays the items in order:

var galleryLength = $('#tout4 img.img_lg').length;
var currentGallery = 0;
setInterval(cycleGallery, 5000);


function cycleGallery(){

    $('#tout4 img.img_lg').eq(currentGallery).fadeOut(300);

    if (currentGallery < (galleryLength-1)){
        currentGallery++;
    } else {
        currentGallery = 0;
    }

    $('#tout4 img.img_lg').eq(currentGallery).fadeIn(300);
}

So how do I rearrange the actual order of the images, and not just the order in which they are selected?

Answer

chad steele picture chad steele · Mar 27, 2013

After much exploration, I decided to take the fisher-yates algorithm and apply it with jquery without requiring cloning, etc.

$('#tout4 img.img_lg').shuffle();

/*
* Shuffle jQuery array of elements - see Fisher-Yates algorithm
*/
jQuery.fn.shuffle = function () {
    var j;
    for (var i = 0; i < this.length; i++) {
        j = Math.floor(Math.random() * this.length);
        $(this[i]).before($(this[j]));
    }
    return this;
};