1

I am trying to create an Animated Responsive Image Grid using this.

In it's source code you can see that the code for those images are physically typed out individually rather than using a function that repeats it for a an 'n' amount of times. If you have a lot of pictures to list, that's painfully repetitive.

Therefore, I created this function:

function showImg() {
  for (var imgNum = 1; imgNum < 100; imgNum++) {
    document.write("<li><a href='#'><img src='img/" +imgNum+ ".jpg'/></a></li>");
  }
}

showImg();

This function is fine, however, every time the page is refreshed, it starts out with the same images in the same order. I don't want that. I want them to start with random images every time the page is refreshed. So I created a new code for that:

function showImg() {
  var imgNum = Math.floor((n+1)*Math.random());
  document.write("<li><a href='#'><img src='img/" +imgNum+ ".jpg'/></a></li>");
}

var n = 100;

for (var i=0; i<n; i++) {
  showImg();
}

Great! Now, a new problem is that sometimes there will be duplicates. I don't want duplicates, not when the first set of images are loaded and not when the images begin to rotate/cycle through the animation. How do I achieve this? Thanks.

1 Answers1

0

Create an array of the numbers 1-100. Then "scramble" them: for 500 times, pick 2 of the array elements and swap their values. Finally, loop through that scrambled array, and show the image associated with the value of that array element.

BrettFromLA
  • 906
  • 1
  • 7
  • 17