Wednesday, August 6, 2008

Event Handlers

JavaScript programs are typically event-driven. Events are actions that occur on the Web page, usually as a result of something the user does, although not always. For example, a button click is an event, as is giving focus to a form element; resizing the page is an event, as is submitting a form. It is these events which cause JavaScript programs to spring into action. For example, if you move your mouse over this phrase, a message will pop-up, courtesy of JavaScript.

An event, then, is the action which triggers an event handler. The event handler specifies which JavaScript code to execute. Often, event handlers are placed within the HTML tag which creates the object on which the event acts:

For example, a hyperlink is subject to a MouseOver event, meaning that its event handler will be triggered when the mouse passes over the link. Therefore, you place the event handler for a hyperlink's MouseOver inside the A tag:

The JavaScript which is called by the event handler may be any valid JavaScript code: a single statement or a series of statements, although most often it is a function call.

The set of all events which may occur, and the particular page elements on which they can occur, is part of the Document Object Model (DOM), and not JavaScript itself (see the earlier section "Document Object Model"). As a result, Netscape and Microsoft do not share the exact same set of events, nor are all page elements subject to the same events between browsers. For example, Internet Explorer 4 supports a MouseOver event for an image while Navigator 4 does not.

The table below illustrates some of the most commonly used events supported in both DOM's. Because the DOM's differ in their event support, the following documents are recommended as an overview of each browser's event support:

Navigator 4: Event Handlers Summary
MSIE 4: DHTML Event Summary

Common Events Event

Occurs when...

Event Handler

click User clicks on form element or link onClick
change User changes value of text, textarea, or select element onChange
focus User gives form element input focus onFocus
blur User removes input focus from form element onBlur
mouseover User moves mouse pointer over a link or anchor onMouseOver
mouseout User moves mouse pointer off of link or anchor onMouseOut
select User selects form element's input field onSelect
submit User submits a form onSubmit
resize User resizes the browser window onResize
load User loads the page in the Navigator onLoad
unload User exits the page onUnload



My Blog List