13.3. Event Handlers in HTMLJavaScript code in a script is executed once: when the HTML file that contains it is read into the web browser. A program that uses only this sort of static script cannot dynamically respond to the user. More dynamic programs define event handlers that are automatically invoked by the web browser when certain events occurfor example, when the user clicks on a button within a form. Because events in client-side JavaScript originate from HTML objects (such as buttons), event handlers can be defined as attributes of those objects. For example, to define an event handler that is invoked when the user clicks on a checkbox in a form, you specify the handler code as an attribute of the HTML tag that defines the checkbox: <input type="checkbox" name="options" value="giftwrap" onclick="giftwrap = this.checked;" > What's of interest here is the onclick attribute. The string value of the onclick attribute may contain one or more JavaScript statements. If there is more than one statement, the statements must be separated from each other with semicolons. When the specified eventin this case, a clickoccurs on the checkbox, the JavaScript code within the string is executed. While you can include any number of JavaScript statements within an event-handler definition, a common technique is to simply use event-handler attributes to invoke functions that are defined elsewhere within <script> tags. This keeps most of your actual JavaScript code within scripts and reduces the need to mingle JavaScript and HTML. Note that HTML event-handler attributes are not the only way to define JavaScript event handlers. Chapter 17 shows that it is possible to specify JavaScript event handlers for HTML elements using JavaScript code in a <script> tag. Some JavaScript developers argue that HTML event-handler attributes should never be usedthat truly unobtrusive JavaScript requires a complete separation of content from behavior. According to this style of JavaScript coding, all JavaScript code should be placed in external files, referenced from HTML with the src attribute of <script> tags. This external JavaScript code can define whatever event handlers it needs when it runs. Events and event handlers are covered in much more detail in Chapter 17, but you'll see them used in a variety of examples before then. Chapter 17 includes a comprehensive list of event handlers, but these are the most common:
For a realistic example of the use of event handlers, take another look at the interactive loan-payment script in Example 1-3. The HTML form in this example contains a number of event-handler attributes. The body of these handlers is simple: they simply call the calculate( ) function defined elsewhere within a <script>. |