0

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.

Simon Carlson
  • 1,919
  • 5
  • 24
  • 35

1 Answers1

1

This question has a useful shuffle function in the accepted answer, which you could use to create your random playlist.

You can then just loop through that with a simple counter, displaying the images that matches that entry in the playlist:

for(n = 0; n <= length; n++) {
    playList.push(n);
}
playList = shuffle(playList);

slidePicture = function () {
    $('.slideshow li').eq(playList[i]).fadeOut(speed, function () {
        var next = (i >= length) ? 0 : i + 1;
        $('.slideshow li').eq(playList[next]).fadeIn(speed);
        i = next;
    });
};

For 1. you can just hide everything and show the picture corresponding to the first entry in the playlist:

$('.slideshow li').hide();
$('.slideshow li').eq(playList[i]).show();

Here's a fiddle showing how it could work. I replaced the images with text for easier testing, and I've chopped and change it a bit. It's rough but hopefully shows the idea.

Community
  • 1
  • 1
James Waddington
  • 2,894
  • 2
  • 15
  • 24