Reputation: 614
Currently I'm using this jquery code that I got from another post here to fade some divs in and out
<script>
$(document).ready(function () {
var divs = $('div[id^="feature-"]').hide(),
i = 0;
(function cycle() {
divs.eq(i).fadeIn(400)
.delay(5000)
.fadeOut(400, cycle);
i = ++i % divs.length;
})();
});
</script>
to cycle through some divs, to make them fade in and fade out in a sort of haphazard slideshow. I would like to randomize the displayed order on page load, for example right now it shows feature-1, then feature-2, then feature-3. How can I get it to randomize that order, like sometimes onload will show feature-3, feature-1, feature-2, and sometimes it will show feature-2, feature-1, feature-3, etc etc. I tried creating an array and then randomizing numbers between 1 and 10 and placing them in indices 0-9, but I couldn't get it to display at all after I tried. Here's a jfiddle to show what it's doing.
Upvotes: 0
Views: 224
Reputation: 1333
Use Math.Random()
http://www.w3schools.com/jsref/jsref_random.asp
Example: Random number from 1 to 6
$(document).ready(function () {
var divs = $('div[id^="feature-"]').hide(),
i = 0,
lastIndex=-1;
(function cycle() {
do{
i = Math.floor((Math.random()*6));
}while(i==lastIndex);
divs.eq(i).fadeIn(400)
.delay(5000)
.fadeOut(400, cycle);
lastIndex=i;
})();
});
Upvotes: 1
Reputation: 57719
$(document).ready(function () {
var divs = $('div[id^="feature-"]').hide(), last_index = false;
function get_random_index(max) {
return Math.floor(Math.random() * max);
}
function cycle() {
var i;
do {
i = get_random_index(divs.length);
} while (i === last_index);
last_index = i;
divs.eq(i).fadeIn(400).delay(5000).fadeOut(400, cycle);
}
cycle();
});
Upvotes: 1