mKay
mKay

Reputation: 311

Random jQuery slideshow

I have a jQuery slideshow which I want to switch to a random image instead of to the next, but I can't find a way to randomize it. Here is my slideshow function which always goes in the same order through my pictures.

$("#header-slide > div:gt(0)").hide();
setInterval(function() {
    $('#header-slide > div:first')
        .fadeOut(2000)
        .next()
        .fadeIn(2000)
        .end()
        .appendTo('#header-slide');     
}, 5000);

and my slider.php file looks like this, with a for every image:

<div>
    <src="..." />
</div>
<div>
    <src="..." />
</div>  

edit: The complete and working solution is now:

$("#header-slide > div").hide();
temp = $('#header-slide > div:eq(' + Math.floor(Math.random() * $('#header-slide > div').length) + ')')
        .fadeIn(2000);
setInterval(function() {
    temp.fadeOut(2000);
    temp = $('#header-slide > div:eq(' + Math.floor(Math.random() * $('#header-slide > div').length) + ')')
        .fadeIn(2000);
}, 5000);

Upvotes: 0

Views: 250

Answers (1)

Jasper Seinhorst
Jasper Seinhorst

Reputation: 1074

You could use the :eq selector with a combination of a random number:

$('.slide:eq(' + (Math.random() * $('.slide.length')-1) + ')')

Upvotes: 2

Related Questions