Show Random Image From Array In Javascript
Solution 1:
Try this function
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var 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";
function imgRandom() {
for (var i = 0; i < 18; i++) {
var rand = imgArray[Math.floor(Math.random() * imgArray.length)];
var image = new Image();
image.src = basePath+rand;
document.body.appendChild(image);
}
}
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 Mmath
->Math
- And the
random
propertie of theMath
object, has to be invoked to return a random numberrandom
->random()
Math.random()
But to your Question
functions take parameters, so could take one param for an array of images
function (imgArr) {...
With this you have access to the passed parameter througimgArr
function can return values, so taken
Math.random
we can go onfunction (imgArr) { return imgArr[Math.floor(Math.random() * imgArr.length)] }
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",...]
Andvar arr=[]
would be equalsvar arr = new Array()
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"]
function imgRandom(imgArr) {
return imgArr[Math.floor(Math.random() * imgArr.length)];
}
console.log(imgRandom(img));
Post a Comment for "Show Random Image From Array In Javascript"