- 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
Some Key JavaScript Concepts
Before we start coding, let's just get aligned on three important points about how JavaScript works.
It's a big moment of enlightenment when you discover that everything in JavaScript that can hold dataa variable, a function, or an arrayis in fact an object. If you aren't technical, all you need to know about objects right now is that an object is a container that can hold related items of data (its properties) and methods (its functions). We access the properties and methods of objects using dot syntax, in a format like this:
var myVariable = someObject.somePropertyOfTheObject
Here's a simple example:
var currentColor = colorPalette.userColorChoice
Notice the dot between the object name (colorPalette) and the object's property (userColorChoice). In this example, the variable (data store) currentColor is set to the value of the property userColorChoice. So, if the value of the property userColorChoice was currently "red", the currentColor variable would be set to "red" by this line of code.
Notice that we put var in front of a variable name when we first declare (create) the variableafter that, we just use the name. This limits the variable's scope (availability) to within the function in which the variable is declared, which ensures that there's no conflict if a variable in another function has the same name. Also, the memory that the variable uses can be released after the function finishes running.
Three important points to note here:
- The variable to the left of the equals sign (=)called the "set" operatoris set to the evaluated result of the right side of the equals sign.
- The properties and methods of an object are accessed with dot syntax.
- Variables have limited, function-level scope (a good thing) if preceded with var when first declared.
It's much easier to understand JavaScript if you have these concepts firmly in your mind.