-2

So,I'm very new to javascript, I realise that there are similar questions out there but I can't see how to make them work with the script I found and I'm trying to learn from.

The script below seems simple and works well but I'd lie to know how to add the code to make the images display in random order.

Please help....

<script>
var i = 0; // Start point
var images = [];
var time = 5000;

// Image List
images[0] = 'images/image1.jpg';
images[1] = 'images/image2.jpg';
images[2] = 'images/image3.jpg';
images[3] = 'images/image4.jpg';


// Change Image
function changeImg(){
    document.slide.src = images[i];

    if(i < images.length - 1){
        i++;
    } else {
        i = 0;
    }

    setTimeout("changeImg()", time);
}


window.onload = changeImg;



</script>

2 Answers2

0

You can make a function to shuffle the array before rendering:

shuffle = function shuffle(array) {
  return array.sort(function () {
    return Math.random() - 0.5;
  });
};

Then in your code call it before showing your pics:

var i = 0; // Start point
var images = [];
var time = 5000;

// Image List
images[0] = 'images/image1.jpg';
images[1] = 'images/image2.jpg';
images[2] = 'images/image3.jpg';
images[3] = 'images/image4.jpg';

// here! 
images = shuffle(images)

// Change Image
function changeImg(){
    document.slide.src = images[i];

    if(i < images.length - 1){
        i++;
    } else {
        i = 0;
    }

    setTimeout("changeImg()", time);
}

Although, i'll be honest there are a number of other ways you can improve your code, as the code you wrote doesn't run as you have it.

JP Silvashy
  • 46,977
  • 48
  • 149
  • 227
  • The code does run as it sits inside other stuff on a simple html page with css and a few other bits and pieces.Your addition did exactly what I was after and worked a treat! As I said, I'm a proper newbie and just experimenting to see what happens. Thanks. – Ian McLaughlin Nov 20 '19 at 21:32
0

This will give you a random number from the array of images, so a random image

Math.round(Math.random()*images.length)