Random Picture Display Tutorial
JavaScript
Objective: Create a web page with random picture display using JavaScript.
Introduction:
More and more educators, students and schools are creating web sites. The creation of web pages are an excellent way to integrate technology into the classroom in the form of a story-telling or reporting activity. Web pages that include images are more interesting to most people than those that don't. However if the pictures never change the page soon grows stale. For this reason some people like to create a bank of images and use a simple script to cause those pictures to be displayed randomly. Here is such a script.
Skill Practice: Random Picture Display using JavaScript
Step 1: Create a folder or directory called randompics.
Step 2: Copy five ".jpg" pictures into the randompics director and name them "pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", and "pic5.jpg".
Step 3: Copy the lines below and paste them into a text file or type them into a text file.
<html>
<head>
<script language="JavaScript">
<!-- Hide this script from old browsers --
var random = Math.random() ;
var picnum = Math.round(random*4)+1;
// -- End Hiding Here -->
</script>
</head>
<body bgcolor="#FFFFFF">
<center>
<br>
Hit Reload to see another picture!
<br>
<script language="JavaScript">
<!-- Hide this script from old browsers --
document.write('<img src=pic'+picnum+'.jpg>')
document.write('<br>')
document.write('picture number = '+picnum)
// -- End Hiding Here -->
</script>
<br>
Hit Reload to see another picture!
</center>
</body>
</html>
Step 4: Save the file in the randompics directory with the name ranpic.html.
Step 5: Use a web browser to open the local page randompics/ranpic.html.
Note: You may edit the ranpic.html page as you desire. You can change the number of images by changing the number in the line that reads, "var picnum = Math.round(random*4)+1". Be sure to make the number (currently 4) one less than the number of images you put in the directory.