samedi 24 janvier 2015

jQuery slideshow with random startpoint

I have my pictures in a list like this:



<ul class="slideshow">
<li><img src="images/slideshow/slide0.jpg" alt="" /></li>
<li><img src="images/slideshow/slide1.jpg" alt="" /></li>
<li><img src="images/slideshow/slide2.jpg" alt="" /></li>
<li><img src="images/slideshow/slide3.jpg" alt="" /></li>
<li><img src="images/slideshow/slide4.jpg" alt="" /></li>
<li><img src="images/slideshow/slide5.jpg" alt="" /></li>
</ul>


And here is my script:



$(function () {
var duration = 6000;
var speed = 700;
var slideshow = $(".slideshow");
var pictures = slideshow.children('li');
var length = pictures.length;
i = 0;
j = 0;

slidePicture = function () {
pictures.eq(i).fadeOut(speed, function () {
while(i == j) {
i = Math.floor(Math.random() * length);
}
pictures.eq(i).fadeIn(speed);
j = i;
});
};

pictures.not(':first').hide();
setInterval(slidePicture, duration);
});


Now this script always starts by showing the same image first. It cannot show the same image twice in a row, but it could show slide0.jpg, then slide1.jpg, then slide0.jpg again and so on. What I want is to



  1. Randomize the starting image so it's different every page load.

  2. When the page loads, create a random "playlist" of images (say first time loading the page the slideshow shows images 3, 1, 0, 5, 2, 4 in that order, next time it loads it's a different order). This is to ensure it doesn't accidently toggle between the same two images.


I tried fixing the 2nd issue by randoming an array containing numbers 0-5 and then shuffling it but my javascript/jQuery skills are very poor and I'm not sure how to proceed. Any help is appreciated.





Aucun commentaire:

Enregistrer un commentaire