Displaying Random Images with Javascript

Marc0

Well-known member
Registered
Joined
Jun 6, 2012
Messages
888
Points
28
If your site is rich with graphics, or if you are displaying digital artwork, then you may want to have a random image from your collection appear when the user enters your site.

This simple HTML creates the page for a random image.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Random Image</title>
     <script language="Javascript" type="text/javascript" src="script10.js"></script>
</head>
<body bgcolor="#FFFFFF">
     <img src="images/spacer.gif" width="305" height="312" id="myPicture" alt="some image" />
</body>
</html>
You can display random images on your page with this script, which uses JavaScript's Math.random method to generate a random number.

Code:
window.onload = choosePic;

var myPix = new Array("images/lion.jpg", "images/tiger.jpg","images/bear.jpg");
function choosePic() {
      randomNum = Math.floor((Math.random() * myPix.length));
      document.getElementById("myPicture").src = myPix[randomNum];
}

Depending on the value of the random number generated by the script, the user is presented with your setting

To display a random image:

1.
Code:
var myPix = new Array ("images/lion.jpg", "images/tiger.jpg", "images/bear.jpg");
As is now familiar, build an array of three images, and stuff it into the variable myPix.

2.
Code:
[CODE]function choosePic() {
[/CODE]

Define the function choosePic().

3.
Code:
randomNum = Math.floor ((Math.random() * myPix.length));
The variable called randomNum gets the value of a math expression that's best read from the inside outwards. Math.random generates a random number between 0 and 1, which is then multiplied by myPix.length, which is the number of items in the array (in this case, it's 3). Math.floor rounds the result down to an integer, which means that the number must be between 0 and 2.

4.
Code:
document.getElementById ("myPicture").src = myPix[randomNum];
This says that the source of the image myPicture is set based on the array myPix, and the value at this moment is dependent on the value of randomNum.
 
Older Threads
Replies
2
Views
4,079
Replies
1
Views
3,060
Replies
30
Views
14,937
Replies
20
Views
15,457
Replies
1
Views
4,143
Newer Threads
Replies
0
Views
2,864
Replies
0
Views
3,088
Replies
1
Views
3,458
Replies
3
Views
5,196
Latest Threads
Replies
0
Views
37
Replies
0
Views
43
Replies
1
Views
449
Replies
1
Views
403
Recommended Threads
Replies
33
Views
23,202
Replies
27
Views
17,914
Replies
7
Views
7,484

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top