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?
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;
};
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 ) } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With