Jack Nilan         Javascript Tutorial        EMail : jacknilan@yahoo.com



Lesson 6 - Random Pictures on Your Page

You can have random pictures appear on your screen. Every time your web page is accessed you can have the computer pick one at random to show. In this lesson we will have 3 pictures and the computer will pick one randomly to show. You can also combine this with the last lesson to have a random picture flash on your screen.

In the HEAD we have some script where we declare an Array (vector) and put some images in the vector.



<head>
<SCRIPT>
pictures = new Array (3);
pictures[0] = new Image;
pictures[0].src = "picture1.jpg";
pictures[1] = new Image;
pictures[1].src = "picture2.jpg";
pictures[2] = new Image;
pictures[2].src = "picture3.jpg";
var index = 0;

</script> </head>

Then somewhere in our HTML body we put :

<script>
var r;
var d;
d = new Date();
var sec = d.getSeconds();
r = sec % 3;
document.write("<img src ="+pictures[r].src + ">");
document.write("lt;br>");
</SCRIPT>


Up above we put 3 pictures in an array. You can put in as many as you want.


Another Way to do this is using the onLoad command instead of the document.write

<head>
<SCRIPT>
pictures = new Array (3);
pictures[0] = new Image;
pictures[0].src = "picture1.jpg";
pictures[1] = new Image;
pictures[1].src = "picture2.jpg";
pictures[2] = new Image;
pictures[2].src = "picture3.jpg";

function putrandompicture()
{ var r;
var d;
d = new Date();
var sec = d.getSeconds();
r = sec % 3;
document.mainpic.src = pictures[r].src;
}
</SCRIPT>


<body onLoad ="putrandompicture();">

<img src = "" name = "mainpic">

Note : the name, in this case mainpic, has to be the same in the body and the function.