Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  106] [ 3]  / answers: 1 / hits: 32031  / 11 Years ago, fri, january 3, 2014, 12:00:00

So my aim is to have a random image generator for a website. So people just click the button, and it loads 1 image out of a the image bank. When i say bank i mean like the file where there located, and would it matter how many image chooses there are?
is there any javascript or html codes for this?



-thanks.


More From » html

 Answers
40

A simple way to do this is as follows:



Name all the pictures with the same name but different number extension: img_1, img_2, img_3...etc.



Define a function that randomly create a img (src) name. For example, if you have 10 images:



The HTML code:



<img id=imageid src=>


And the JS code:



function randomImg(){
var randomNumber = Math.floor(Math.random() * 10) + 1;
var imgName = img_ + randomNumber;
document.getElementById(imageid).src= YOUR_IMG_PATH + / + imgName ;
}


Hope it helps!



EDIT: If you have a .jpg or .png image, make sure to include that in the function or it won't work. For example for a JPG image:



function randomImg(){
var randomNumber = Math.floor(Math.random() * 12) + 1;
var imgName = img_ + randomNumber + .jpg;
document.getElementById(greenbox).src= YOUR_IMG_PATH + / + imgName ;
}

[#73404] Thursday, January 2, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Mar 17, 20, 00:00, 4 Years ago
;