- 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
Creating the Image Path
Because the images are in a folder called images at the same level as the page, we need to first assemble the relative path to the selected image. It needs to look like this:
images/pic5.jpg
All we need to do is replace the number in this path with the random number we just generated. To do this, we'll concatenate (join together) two strings of text containing the unchanging part of this path name and the variable holding the image number, using use the plus (+) operator. Note that when used between numbers, the + operator adds the numbers together, but when used between text strings, it concatenates them into a single string:
var mySrc = "images/pic" + randomNum + ".jpg"
For clarity, I've added some spaces, which JavaScript ignores. Notice how the + operators and the variable (shown in boldface) are placed between the two strings that contain the unchanging parts of our path name. If the current random number was 2, this line would give us this string:
images/pic2.jpg
Our new variable mySrc now contains the correct URL relative to the page.