|
There's more than one way to call a FunctionThe act of triggering a Function is referred to as "calling" a Function. There are a variety of ways you can do this. Mouse actions are among the most common type of Events that are used to call Functions, but onLoad Events are also used frequently. If you want something to happen when a page is finished loading, you can put an onLoad Event Handler into the <BODY> tag and use it to call a Function, like this:
Using the onLoad Event Handler is a good way to initiate an action as soon as the page loads. You can run two or more scripts with the onLoad function at the same time (Running 2 Scripts onLoad). In the rest of this section, we'll see that using an Event Handler isn't the only way to call a Function.
If you want a Function to execute immediately upon being read, without waiting for the rest of the page to load, you can add a line to the script section in the head section of the HTML document that merely contains the name of the Function. The Function will be called as soon as that line is read. If you do this, it's a good idea to make sure you've already declared the Function at an earlier point in the script, or else there will be an error when JavaScript tries to call a Function that doesn't exist yet (because it hasn't even been read yet). Here's an example of how to call a Function from within the main script area of the <HEAD> section of an HTML document:
This Function would pop up an alert box stating "I'm doing something." before the body of the page has even loaded into the browser. Although this is a relatively pointless thing to do, we will soon see examples where this sort of technique makes sense. You can call a Function within the body section of an HTML document by using the <SCRIPT> </SCRIPT>tags. We've already seen some examples of this in previous modules. This is done as follows:
This approach, where you add <SCRIPT> </SCRIPT> tags alongside ordinary HTML tags, is especially useful if you're using the document.write() Method, since the Method will begin writing at that specific point in the HTML document while it is in the process of loading.
Finally, a Function can be called from within another Function, merely by including its name in a line of that Function. Here's how that looks:
Calling Functions from within other Functions is one of the most common ways that Functions are called. Ultimately, however, it always takes a user action (an Event) somewhere at the beginning to get the ball rolling. |