IslandKing
IslandKing

Reputation: 27

Javascript Random image from a Directory

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

Upvotes: 1

Views: 1718

Answers (1)

rpax
rpax

Reputation: 4496

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]+"' />"

}

Upvotes: 1

Related Questions