- 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
Adding the Image Element to the Page
Next, we need to "get" the div element into which the image element goes. This is easy, as the div has an ID, and we can use the getElementById method to get it:
var theDiv=document.getElementById("display");
Now we have the div as an object, and we can add a child object to it. A child object of an element is nested inside of the parent element's opening and closing tag, which is exactly where we want our new image element to go. The appendChild method takes one argumentthe element to add, which we're holding ready to go in the myImgEl variable:
theDiv.appendChild(myImgEl);
When the code runs, the new image element will be inserted into the div, and this will cause the randomly selected image to be displayed.