Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery move elements into a random order

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?

like image 280
mheavers Avatar asked Mar 16 '11 17:03

mheavers


2 Answers

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;
};
like image 167
chad steele Avatar answered Nov 20 '22 11:11

chad steele


You can also use the common JavaScript Array randomize sorter, also commented here and here:

$('<my selector>').sort( function(){ return ( Math.round( Math.random() ) - 0.5 ) } );
like image 8
fguillen Avatar answered Nov 20 '22 10:11

fguillen