- 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
Assembling the Image Element
Perhaps the coolest aspect of DOM scripting is being able to conjure up a brand-new HTML element and add it into the page, as we'll do now. All the DOM scripting methods belong to the built-in document object. Let's start by creating an image element:
var myImgEl = document.createElement("img");
This element now exists in memory as an object called myImgEl. We need to do a little more to it before we actually add it to the pagewe have to add the src attribute with the image path we made, as well as the required descriptive alt attribute. We can't see the element until we add it to the page, so we just have to carry on, believing that we're doing this bit correctly. We set the two attributes as properties of the objectnote the dots. The setAttribute method requires two arguments: the name of the attribute and its value:
myImgEl.setAttribute("src",mySrc); myImgEl.setAttribute("alt","my old car");
Now the image element is good to go.