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

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

  • Print
  • + Share This
From the author of The Coding Plan

The Coding Plan

It's helpful to map out the high-level flow of the code before starting. In this example, each time the page loads, the JavaScript will call a function when the page finishes loading. That function will do the following:

  1. Generate a random number between 1 and 5.
  2. Assemble a URL comprising the folder path and filename, using the random number in the filename.
  3. Dynamically create an image element with the URL as the src attribute.
  4. Add the image element into a div element that's already in the page markup, causing the image to display on the page.

Before we do this, we need some markup, which for this example is very simple:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Random Picture Rotation</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<script type="text/javascript">

  // all the JavaScript goes here

</script>
<h1>Car for sale!</h1>
<p><a href="random_images.html" >show another random pic</a></p>
<div id="display"></div>
</body>
</html>

I've boldfaced the only important line. This div, which has an ID of "display", has nothing inside it. That's where our JavaScript will add an image tag with the source (in this case, the relative URL) of the selected picture. Notice also that I have added a script element, inside of which our JavaScript will reside.

  • + Share This
  • 🔖 Save To Your Account