0

I have tried generating random images using Javascript, but it couldn't work. My code is below; I don't know if the function is correct or not.

//var imageDir = document.images;
var imageDir = [ 10 ];

var imageDir =
    [
    "cards/1.png",
    "cards/2.png",
    "cards/3.png",
    "cards/4.png",
    "cards/5.png",
    "cards/6.png",
    "cards/7.png",
    "cards/8.png",
    "cards/9.png",
    "cards/10.png"

    ];
displayRandomImage = function(i, numberOfImages) {
    for (var i = 0; i < imageDir.length; i++, i = parseInt(Math.random() * i))
    {
        return i = Math.random(i, numberOfImages - 1);
    }
};

var imageDir = displayRandomImage(imageDir, 10);

for (var i = 0; i < imageDir.length; i++) {
    document.getElementById("randimage" + i).innerHTML = "<img src='" + imageDir[ i ] + "' />"
}
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
IslandKing
  • 27
  • 2
  • 12
  • 1
    For starters, you probably don't want to use the same variable as a function parameter as a loop variable (`i`) – fejese Feb 24 '14 at 21:24
  • 1
    you can check out http://stackoverflow.com/questions/14004318/show-random-image-from-array-in-javascript?rq=1 – sopanha Feb 24 '14 at 21:29
  • Do you want each image to only display once? So you would basically be showing all of the images exactly once, but in a random order? Or is it truly random, so you would be showing 10 images, but the same image could be displayed more than once? – talemyn Feb 24 '14 at 21:39
  • To display all images randomly and more than once – IslandKing Feb 24 '14 at 22:59

1 Answers1

0

Do you want to just pick a random image? Or display all the images in the array in random order? If the latter, try this.

Source of shuffle function.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] =     o[j], o[j] = x);
    return o;
};

var imagePaths = shuffle([
                "cards/1.png",
                "cards/2.png",
                "cards/3.png",
                "cards/4.png",
                "cards/5.png",
                "cards/6.png",
                "cards/7.png",
                "cards/8.png",
                "cards/9.png",
                "cards/10.png"]);

for(var i = 0; i < imagePaths.length; i++) {
    document.getElementById("randimage" + i).src = imagePaths[i];
}

See here for an example of this in action: http://jsfiddle.net/nSaAh/

Community
  • 1
  • 1
davnicwil
  • 28,487
  • 16
  • 107
  • 123