Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
Like this article? We recommend Reviewing the Working Page

Reviewing the Working Page

If we load the page a few times, the images appear randomly, as shown in Figure 4.

Figure 4 Each time we load the page, one of the five images will be displayed.

Our complete page code looks like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>Random Picture Rotation - a JavaScript tutorial by Charles Wyke-Smith</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
body {font-family:verdana, sans-serif;}
 h1, p, div {
h1 {
        border-top:3px solid #069;
div#display {
        border-bottom:2px solid #069;
<script type="text/javascript">
//Random Picture Rotation by Charles Wyke-Smith -
// A script that loads a random picture each time the page is loaded
// This script assumes your images are named pic1.jpg, pic2.jpg, etc.
// Also assumes images in folder called images at same level as HTML doc
// Set the picCount variable equal to the number of images to rotate
// This script can be used freely if this message is kept intact

window.onload = pickAPic;
function pickAPic() {
var randomNum;  // a variable to hold the random number
var picCount = 5; // the number of pictures to rotate
randomNum =  Math.floor(Math.random()*picCount)+1;
var mySrc="images/pic"+randomNum+".jpg"
var myImgEl = document.createElement("img");
myImgEl.setAttribute("alt","my old car");
var theDiv = document.getElementById("display");
<h1>My old car!</h1>
<p><a href="random_images.html">show another random pic</a></p>
<div id="display"></div>
  • + Share This
  • 🔖 Save To Your Account