Skip to content Skip to sidebar Skip to footer

Show Random Image From Array In Javascript

I want to select random images from imgArray to print 16 different images at the same time but can't fill the imgRandom function. img = new imgArray(7); img[0]='1.png'; img[1]='2.p

Solution 1:

Try this function

functiongetRandomImage(imgAr, path) {
    path = path || 'images/'; // default path herevar num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<img src="' + path + img + '" alt = "">';
    document.write(imgStr); document.close();
}

Call the function

getRandomImage(ARRAY-VARIABLE, '/images/')

Refer LIVE DEMO. You will see change in image for every refresh

Solution 2:

Use the following code:

var imgArray = ['1.png', '2.png', '3.png', '4.png', '5.png', '6.png', '7.png', '8.png'];
var basePath="YOUR_FOLDER_PATH_HERE";

functionimgRandom() {
    for (var i = 0; i < 18; i++) {
        var rand = imgArray[Math.floor(Math.random() * imgArray.length)];
        var image = newImage();
        image.src = basePath+rand;
        document.body.appendChild(image);
    }
}

Live Demo | Source

Solution 3:

There are some things in your code i would like to point out

  • There is no imgArray in javascript per default (maybe its a constructor of your's)
  • You want an Array

  • Javascript is case sensitiv, and the Math object in js has an capital M

    • math -> Math
  • And the random propertie of the Math object, has to be invoked to return a random number
    • random -> random()
    • Math.random()

But to your Question

  1. functions take parameters, so could take one param for an array of images

    function (imgArr) {...With this you have access to the passed parameter throug imgArr

  2. function can return values, so taken Math.random we can go on

    function (imgArr) { return imgArr[Math.floor(Math.random() * imgArr.length)] }

  3. You don't have to "Dim" Array, and predefine the Elements you gonna put in, you can just do sth. like

    var imgArr = ["img01.png","img02.png",...]And var arr=[] would be equals var arr = new Array()

  4. So calling this function with your Array couldlook like


var img = ["1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png", "8.png"]
     functionimgRandom(imgArr) {
        return imgArr[Math.floor(Math.random() * imgArr.length)];
    }
 console.log(imgRandom(img));

Post a Comment for "Show Random Image From Array In Javascript"