HTML and CSS Reference
In-Depth Information
Figure 7.7 A function is called after the event is triggered. The function “handles”
the event.
Calling a Function from JavaScript. In the first examples of this chapter, func-
tions were defined in one JavaScript script and called from another. Although it is valid
to define and call the function from the same JavaScript program, it is often desirable to
define the function in the head of the document, to be sure it has been defined before it
is called. Then you can call the function from a link, an event, or another JavaScript pro-
gram. Because the document is defined within the <body></body> tags, the body is often
the place from where you will call functions. The general rule of thumb is: If your script
is designed to write data to the page, put the <script></script> tags within the
<body></body> tags. Example 7.2 called a function from one JavaScript program within
the body, but defined the function in another JavaScript program within the head.
Finally, you might want to store function definitions in an external library (.js file)
where they can be reused and shared by other programs.
Scope of Variables in Functions. The scope of a variable describes where the vari-
able is visible in the program; that is, where it can be used in the program. Variables
declared outside of functions are global in scope, meaning they can be used or changed
anywhere in the program. A variable is also global if declared within a function unless
it is declared within a function with the var keyword. The var keyword makes the vari-
able local in scope; that is, the variable can be used only within the function where it is
defined and is no longer visible once the function ends.
 
Search WWH ::




Custom Search