I have a library of images and I want to create a Javascript file so that each time I click a button it would generate random images from a directory and display 4 images from that Directory
Asked
Active
Viewed 1,643 times
1
-
1Possible duplicate of http://stackoverflow.com/questions/5809188/script-to-display-an-image-selected-at-random-from-an-array-on-page-load – ambodi Feb 23 '14 at 22:50
1 Answers
1
You're not specifying how images are obtained, so I guess the images are stored in an array of strings. Anyway, the first thing you need is some kind of shuffle algorithm, for sure.
Check out this link: http://dzone.com/snippets/array-shuffle-javascript
Adapting the code to your needs:
var arr = [
"http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png",
"http://img.bananity.com/media/512/512/bananities/8060a5cf4f9eae8ecff79720db58c2dfacf707344fcb.png",
"http://www.socialtalent.co/images/blog-content/so-logo.png",
"http://www.logoeps.net/wp-content/uploads/2013/06/stackoverflow_logo.jpg",
"http://i22.photobucket.com/albums/b302/Creyeknife/SO_concept1.jpg"
];
getRndImgs = function(o,numberOfImgs){
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o.slice(0,numberOfImgs-1);
};
So you can call later:
var imagesToShow=getRndImgs(arr,4);
And display them somewhere
for (var i=0;i<imagesToShow.length;i++) {
document.getElementById("div_"+i).innerHTML="<img src='"+imagesToShow[i]+"' />"
}

rpax
- 4,468
- 7
- 33
- 57
-
-
o is the array of images. i and j are for accessing the array elements, in different indexes. x is a variable for exchanging items of the array. – rpax Feb 26 '14 at 18:25