- 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
Triggering the Function from the Load Event
Let's start our coding by simply having our function pop up an alert dialog (the little window with an OK button) when the function is called, so we can tell that we're calling it successfully. We add all our JavaScript between the script tags in the markup:
<script type="text/javascript"> function pickAPic () { alert ("called"); } <script>
A function has a name (in this case, pickAPic) followed by parentheses. Next come the braces ({}) that contain the code that runs when the function is called; for now, a single line to display our alert. Functions don't run when they load into the browseronly when they're explicitly called from elsewhere in the code.
Now that we have a function, let's see what it takes to call it when the load event fires. We can trigger our function in response to the load event by using the onload event handler, which is a property of the JavaScript's built-in Window object, like this:
window.onload=pickAPic;
If we load our page now, after a very brief pause while the content loads, the dialog in Figure 2 pops up.
Figure 2 The dialog displays when the function is triggered by the load event.
Knowing how to make JavaScript wait patiently like this until the page is ready is a key coding skill. In an online application, the onload handler will typically trigger a function (often called init for initialize) that sets up the initial state of the application, performing tasks such as adding click event listeners to elements so that they respond to mouse clicks, and making Ajax requests to the server to pull in data that the application needs from the database. (I'll talk about event listeners in a future article.) If you want to work out what's going on in a JavaScript-driven page, start by finding the onload handler and go from there.