VCA225 Digital Production

Random Images

Ever visit a web page that has a different picture every time that you visit or click the refresh button? It's a pretty simple trick to accomplish with a little bit of Javascript.

Exercise

Create a web page that contains a randomly generated image.

  1. Create a folder called "yourNameRandom" inside your root folder.
  2. Download this zip file; it contains a folder called "randomImages" which contains nine images. Put the folder inside the "yourNameRandom" folder.
  3. Create a new html document and call it "random.html". Save it inside the "yourNameRandom" folder, next to the "randomImages" folder.
  4. Put some text on the page ("Look at this picture" or something similar).
  5. Now we're going to add some Javascript. In the place you want the picture to appear (before or after the text) write:

<script language="javascript">
document.write("<img src = randomImages/pic" + Math.ceil (Math.random() * 9) + ".jpg>")

</script>

This script does a few things. The "document.write" part actually generates the "img src" code for you at the spot in the html markup specified. The "Math.ceil (Math.random()*9)" function generates a random number from 1-9. It then combines the name of the picture file ("pic"), with the random number, and the "jpg" extension. So it will write a URL to "pic1.jpg" or "pic2.jpg" or "pic3.jpg," etc. Pretty slick, huh?

  1. Save your file and try it out in a browser. Hold down the shift key and hit the refresh button. Does the image change? Try it again.
  2. Now try duplicating the "document.write" line three times in a row. Your page should now have 3 randomly generated pictures.
  3. For added fun, add the meta refresh tag:

<meta http-equiv="refresh" content="3" />

 

This will cause the pictures to update every 3 seconds (or whatever amount you set). Note that this can get really annoying and there are better ways of doing this (like with Flash). Save this version with a different name like "refreshRandom.html"

  1. FTP the "yourNameRandom" to your server space.
  2. Update your home page so that the Random link points to "random.html."

Point Breakdown

4 pts

Went well above and beyond and created something special.

3 pts

Went above and beyond requirements (customized the page; used your own images, etc.).

2 pts

Did what was required.

1 pts

Missing one or more required elements or contains one or more errors.

0 pts

Poor showing; mostly incomplete or full of errors.

 

Course Outline

Syllabus

Student Resources