JavaScript: The Definitive Guide

Previous Chapter 6
Functions
Next
 

6.5 Event Handlers

An event handler is a special-purpose function, one that is used only in client-side JavaScript. Event-handler functions are defined unusually--instead of using the function keyword (or the Function() constructor) and being defined as part of a JavaScript program, they are defined as fragments of JavaScript within the HTML tags of certain elements on a web page.

Event-handler functions are also unusual in how they are used. They are not usually invoked by your JavaScript program; instead, they are invoked by the web browser itself, whenever certain "events" occur within the element with which they are associated. For example, you can associate an event handler with a button in an HTML form. When the user clicks on the button, the JavaScript code in the event handler will be automatically invoked by the browser. The following piece of HTML code creates a button with the words "Click me!"; clicking the button runs an piece of JavaScript code that adds together two numbers and displays the result in a dialog box:

<FORM>
<INPUT TYPE="submit" VALUE="Click me!" 
       onClick="var sum=1+2; alert(sum);">
</FORM>

This piece of JavaScript code is actually a function. That is, defining an event handler in an HTML tag does create a JavaScript function object, just as other function definitions do, and this object can be used as other function objects are. The main difference is that the function will be invoked automatically by the browser in response to appropriate user actions.

Event handlers are part of client-side JavaScript, not part of the core language. Therefore, their definition and use will be described in greater detail in Chapter 10, Client-Side Program Structure.


Previous Home Next
Built-in Functions Book Index Objects

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell
Hosted by uCoz