- 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
How the Rotating Images Code Works
In this example, which you can see here, each time the page loads it randomly displays one of five images that I took of my car when I sold it on craigslist. I'll show you how to write the JavaScript to do this.
We begin by putting the images (carefully named pic1.jpg, pic2.jpg, pic3.jpg, pic4.jpg and pic5.jpg) into a folder called images at the same level as the HTML file. As you can see, the only difference among these filenames is the number. Our strategy will be to generate this number randomly and add it into the filename that our code will use to select the picture.