- Random Picture Rotation with JavaScript
- How the Rotating Images Code Works
- The Coding Plan
- Some Key JavaScript Concepts
- Detecting the Load Event
- Triggering the Function from the Load Event
- Generating Random Numbers
- Creating the Image Path
- DOM Scripting
- Assembling the Image Element
- Adding the Image Element to the Page
- Reviewing the Working Page
- Summary
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:
- Generate a random number between 1 and 5.
- Assemble a URL comprising the folder path and filename, using the random number in the filename.
- Dynamically create an image element with the URL as the src attribute.
- 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.