- How the Rotating Images Code Works
- The Coding Plan
- 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
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:
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"
Our new variable mySrc now contains the correct URL relative to the page.