Click to See Complete Forum and Search --> : Loading a Random Image
python
11-24-2003, 09:51 AM
I am looking to be able to load a randomly selected image from a certain folder into a HTML page.
I had thought about creating an array that contained the path to the individual images and then creating a random number from 0 to size of array that could be used to determine which picture to display, however i cannot get it woring.
Any help would be much appreciated either with this approach or another that would help solve my problem.
Cheers.
fredmv
11-24-2003, 09:52 AM
Welcome to the forums.
Please provide some source code or a link if you have one, it will make it much easier for us to help you.
neil9999
11-24-2003, 10:15 AM
You could pick a random number like this:
var numpics=2
var rannum=(Math.floor(Math.random() * (1 - numpics)) + numpics)+1;
Then use some if statements, like this:
if(rannum==1){document.write("<img src=\"image1.gif\" width=\"100\" height=\"200\">")}
if(rannum==2){document.write("<img src=\"image2.gif\" width=\"100\" height=\"200\">")}
change var numpics to the number of possible pictures that could be displayed, then do the same amount of if statements: one for each number between 1 and numpics.
Neil
python
11-24-2003, 10:21 AM
The site that I'm working on can be found at
http://alex.firemirror.com
The two images on the right of the page i want to be chosen randomly when the page is loaded.
neil9999
11-24-2003, 10:41 AM
Then use something like this:
<html>
<head>
<script language="javascript">
function ranpic(){
var numpics=2
var rannum=(Math.floor(Math.random() * (0 - numpics)) + numpics)+1;
if(rannum==1){document.write("<img src=\"pic11.jpg\" width=\"150\" height=\"111\">")}
if(rannum==2){document.write("<img src=\"pic12.jpg\" width=\"150\" height=\"144\">")}
}
</script>
</head>
<body onload="ranpic()">
</body>
</html>
Remember to change the height and width abituries if needbe.
Neil
python
11-24-2003, 11:05 AM
OK, I see how this would choose between two random images, but how do I get it to put the randomly chosen image in the correct place on the page?
neil9999
11-24-2003, 11:33 AM
Say you've got a table with a cell in which you want the picture, use something like this:
<html>
<head>
<script language="javascript">
function ranpic(){
var numpics=2
var rannum=(Math.floor(Math.random() * (0 - numpics)) + numpics)+1;
if(rannum==1){document.getElementById('piccell').innerHTML="<img src=\"pic11.jpg\" width=\"150\" height=\"111\">"}
if(rannum==2){document.getElementById('piccell').innerHTML="<img src=\"pic12.jpg\" width=\"150\" height=\"144\">"}
}
</script>
</head>
<body onload="ranpic()">
<table border="0" width="100%">
<tr>
<td width="50%"></td>
<td width="50%" id="piccell"></td>
</tr>
</table>
</body>
</html>
Neil
python
11-24-2003, 11:46 AM
Thanks for all the help guys, I've got it working now. All I need to do is make sure that it isn't the same image chosen both times, but that shouldn't be too difficult.