JavaScript Editor JavaScript Debugger     JavaScript Editor 



Team LiB
Previous Section Next Section

The Basic Event Model

Before discussing more modern event models, let’s discuss the basic event model common to nearly all JavaScript-supporting browsers. The basic model is simple, widely supported, and easy to understand. At the same time it has sufficient flexibility and features so that most developers never need more than it in the course of day-to-day programming tasks. Thankfully, proprietary browser event models and the newer DOM2 model are compatible with this basic model. This means that you can stick to the basic model even in the most recent browsers. The advantage of using proprietary features or DOM2 is that you get even more flexibility and advanced behaviors that are useful when building Web-based JavaScript applications.

Event Binding in (X)HTML

HTML supports core event bindings for most elements. These bindings are element attributes, like onclick and onmouseover, which can be set equal to the JavaScript that is to be executed when the given event occurs at that object. As the browser parses the page and creates the document object hierarchy, it populates event handlers with the JavaScript code bound to elements using these attributes. For example, consider the following simple binding that defines a click handler for a link:

<<a href="/" onclick="alert('Now proceeding
to DOM H.Q.');">>Read about the W3C DOM<</a>>
Note 

Although traditional HTML is case-insensitive, XHTML requires lowercase element and attribute names. So while you may see many Web pages using “onClick” or occasionally “ONCLICK,” the all lowercase “onclick” is more correct.

Most of the (X)HTML event attributes cover user actions, such as the click of a mouse button or a key being pressed. The primary event handler attributes supported in (X)HTML are summarized in Table 11-2.

Table 11-2: Basic Events and Their Corresponding Event Handler Attributes in (X)HTML

Event Attribute

Event Description

Allowed Elements Under
Standard (X)HTML

onblur

Occurs when an element loses focus, meaning that the user has activated another element, typically either by clicking the other element
or tabbing to it.

<a>, <area>, <button>, <input>, <label>, <select>, <textarea>
Also <applet>, <area>, <div>, <embed>, <hr>, <img>, <marquee>, <object>, <span>, <table>, <td>, <tr>
In IE4+ and N4 also <body>
In N4 also <frameset>, <ilayer>, <layer>

onchange

Signals that the form field has lost user focus and its value has been modified during this
last access.

<input>, <select>, <textarea>

onclick

Indicates that the element has been clicked.

Most display elements*
In IE4+ also <applet>, <font>

ondblclick

Indicates that the element has been
double-clicked.

Most display elements*
In IE4+ also <applet>, <font>

onfocus

Indicates that the element has received focus; in other words, it has been selected by the user for manipulation or data entry.

<a>, <area>, <button>, <input>, <label>, <select>, <textarea>
In IE4+ also <applet>, <div>, <embed>, <hr>, <img>, <marquee>, <object>, <span>, <table>, <td>, <tr>
In IE4+ and N4 also <body>
In N4 also <frameset>, <ilayer>, <layer>

onkeydown

Indicates that a key is being pressed down with focus on the element.

Most display elements*
In IE4+ also <applet>, <font>

onkeypress

Indicates that a key has been pressed and released with focus on the element.

Most display elements*
In IE4+ also <applet>, <font>

onkeyup

Indicates that a key is being released with focus on the element.

Most display elements*
In IE4+ also <applet>, <font>

onload

Indicates that the object (typically a window or frame set) has finished loading into the browser.

<body>, <frameset>
In IE4+ also <applet>, <embed>, <link>, <script>, <style>
In N4 also <ilayer>, <layer>
In IE4+ and N4 also <img>

onmousedown

Indicates the press of a mouse button with focus on the element.

Most display elements*
In IE4+ also <applet>, <font>

onmousemove

Indicates that the mouse has moved while over the element.

Most display elements*
In IE4+ also <applet>, <font>

onmouseout

Indicates that the mouse has moved away from
an element (i.e., is no longer above the element).

Most display elements*
In IE4+ also <applet>, <font>
In N4 also <ilayer>, <layer>

onmouseover

Indicates that the mouse has moved over
the element.

Most display elements*
In IE4+ also <applet>, <font>
In N4 also <ilayer>, <layer>

onmouseup

Indicates the release of a mouse button with focus on the element.

Most display elements*
In IE4+ also <applet>, <font>

onreset

Indicates that the form is being reset, possibly by the press of a reset button.

<form>

onselect

Indicates the selection of text by the user, typically by highlighting it with the mouse.

<input>, <textarea>

onsubmit

Indicates that the form is about to be submitted, generally the result of activating a Submit button.

<form>

onunload

Indicates that the browser is navigating away from the current document, and unloading it from the window or frame.

<body>, <frameset>

Note 

In Table 11-2, Internet Explorer Netscape browser versions are abbreviated with “IE” and “Netscape” followed by the version number. Netscape 6 implements portions of the W3C DOM2 event model and is discussed in a later section. Also, “most display elements*” means all elements except <<applet>>, <<base>>, <<basefont>>, <<bdo>>, <<br>>, <<font>>, <<frame>>, <<frameset>>, <<head>>, <<html>>, <<iframe>>, <<isindex>>, <<meta>>, <<param>>, <<script>>, <<style>>, and <<title>>.

The example shown here illustrates these events in action.

<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>HTML Event Bindings<</title>>
<<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />>
<</head>>
<<body onload='alert("Event demo loaded");' onunload='alert("Leaving
 demo");'>>
<<h1 align="center">>HTML Event Bindings<</h1>>
<<form action="#" method="get" onreset="alert('Form reset');"
      onsubmit="alert('Form submit');return false;">>
<<ul>>
<<li>>onblur: 
<<input type="text" value="Click into field and then leave"
 size="40" onblur="alert('Lost focus');" />><<br />><<br />><</li>>
<<li>>onclick: <<input type="button" value="Click me" 
onclick="alert('Button click');" />><<br />><<br />><</li>>

<<li>>onchange: <<input type="text" value="Change this text then leave"
 size="40" onchange="alert('Changed');" />><<br />><<br />><</li>>

<<li>>ondblclick: <<input type="button" value="Double-click me"
 ondblclick="alert('Button double-clicked');" />><<br />><<br />><</li>>

<<li>>onfocus: <<input type="text" value="Click into field"
 onfocus="alert('Gained focus');" />><<br />><<br />><</li>>
<<li>>onkeydown: 
<<input type="text" value="Press key and release slowly here" size="40"
 onkeydown="alert('Key down');" />><<br />><<br />><</li>>

<<li>>onkeypress: 
<<input type="text" value="Type here" size="40" onkeypress="alert('Key
 pressed');" />><<br />><<br />><</li>>

<<li>>onkeyup: <<input type="text" value="Press a key and release it" size="40"
 onkeyup="alert('Key up');" />><<br />><<br />><</li>>
<<li>>onload:  An alert was shown when the document loaded.<<br />><<br />><</li>>

<<li>>onmousedown: 
<<input type="button" value="Click and hold" onmousedown="alert('Mouse down');" />><<br />><<br />><</li>>
<<li>>onmousemove: Move mouse over this
<<a href="#" onmousemove="alert('Mouse moved');">>link<</a>><<br />><<br />><</li>>

<<li>>onmouseout: Position mouse 
<<a href="#" onmouseout="alert('Mouse out');">>here<</a>> and then away.
<<br />><<br />><</li>>
<<li>>onmouseover: Position mouse over this 
<<a href="#" onmouseover="alert('Mouse over');">>link<</a>><<br />><<br />><</li>>
<<li>>onmouseup: 
<<input type="button" value="Click and release"
  onmouseup="alert('Mouse up');" />><<br />><<br />><</li>>
<<li>>onreset: <<input type="reset" value="Reset Demo" />><<br />><<br />><</li>>
<<li>>onselect: <<input type="text" value="Select this text" size="40"
                     onselect="alert('selected');" />><<br />><<br />><</li>>
<<li>>onsubmit: <<input type="submit" value="Test submit" />><<br />><<br />><</li>>
<<li>>onunload: Try to leave document by following this 
              <<a href="/">>link<</a>><<br />><<br />><</li>>
<</ul>>
<</form>>
<</body>>
<</html>>

Browsers might support events other than those defined in the (X)HTML specification. Microsoft in particular has introduced a variety of events to capture more complex mouse actions (such as dragging), element events (such as the bouncing of <<marquee>> text), and data-binding events signaling the loading of data. Some of these events are described in more detail in Table 11-3. These events are non-standard, and, with a few exceptions, are most useful in an intranet environment where you can be guaranteed of browser compatibility. We won’t discuss these events in great depth here, but you can find more information on msdn.microsoft.com. A Google Web search for site:msdn.microsoft.com dhtml events should also turn them up.

Table 11-3: A Sample of Non-standard Event Handlers Available in Netscape and Internet Explorer
Event AttributeEvent DescriptionPermitted ElementsCompatibility

onabort

Triggered by the user aborting the image load via the Stop button or similar mechanism.

<img>

Netscape 3, 4–4.7
Internet Explorer 4+

onactivate

Fires when the element becomes the active element, that is, the element that will have focus when its parent frame or window has focus.

Most display elements

Internet Explorer 5.5+

onafterprint

Fires after user prints
document or previews
document for printing.

<body>, <frameset>

Internet Explorer 5+

onafterupdate

Fires after the transfer of
data from the element to
a data provider.

<applet>, <body>, <button>, <caption>, <div>, <embed>,
<img>, <input>, <marquee>, <object>, <select>, <table>,
<td>, <textarea>, <tr>

Internet Explorer 4+

onbeforeactivate

Fires just before the element becomes the active element (see onactivate)

Most display elements

Internet Explorer 5.5+

onbeforecopy

Fires just before selected content is copied and placed
in the user's system clipboard.

<a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <caption>, <center>, <cite>, <code>, <custom>, <dd>, <dfn>, <dir>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> – <h6>, <i>, <img>, <label>, <legend>, <li>, <listing>, <menu>, <nobr>, <ol>, <p>, <plaintext>, <pre>, <s>, <samp>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <td>, <textarea>, <th>, <tr>, <tt>, <u>, <ul>

Internet Explorer 5+

onbeforecut

Fires just before selected content is cut from the document and added to
the system clipboard.

<a>, <address>, <applet>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <center>, <cite>, <code>, <custom>, <dd>, <dfn>, <dir>, <div>, <dl>, <dt>, <em>, <embed>, <fieldset>, <font>, <form>, <h1> – <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <listing>, <map>, <marquee>, <menu>, <nobr>, <ol>, <p>, <plaintext>, <pre>,
<rt>, <ruby>, <s>, <samp>, <select>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <u>, <ul>, <var>, <xmp>

Internet Explorer 5+

onbeforedeactivate

Fires just before the active element changes from the current element to some other.

Most display elements

Internet Explorer 5.5+

onbeforeeditfocus

When using design mode or the contenteditable feature, fires when a contained element receives focus for editing.

Most elements

Form fields in Internet Explorer 5, all elements in Internet Explorer 5.5+

onbeforepaste

Fires before selected content is pasted into a document.

<a>, <address>, <applet>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <center>, <cite>, <code>, <custom>, <dd>, <dfn>, <dir>, <div>, <dl>, <dt>, <em>, <embed>, <fieldset>, <font>, <form>, <h1> – <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <listing>, <map>, <marquee>, <menu>, <nobr>, <ol>, <p>, <plaintext>, <pre>,
<rt>, <ruby>, <s>, <samp>, <select>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <u>, <ul>, <var>, <xmp>

Internet Explorer 5+

onbeforeprint

Fires before user prints document or previews
document for printing.

<body>, <frameset>

Internet Explorer 5+

onbeforeunload

Fires just prior to a document being unloaded from a window.

<body>, <frameset>

Internet Explorer 4+

onbeforeupdate

Triggered before the transfer
of data from the element to the data provider. Might be triggered explicitly, by a loss of focus
or by a page unload forcing a data update.

<applet>, <body>, <button>, <caption>, <div>, <embed>,
<hr>, <img>, <input>, <object>, <select>, <table>, <td>, <textarea>, <tr>

Internet Explorer 4+

onbounce

Triggered when the bouncing contents of a marquee touch one side or another.

<marquee>

Internet Explorer 4+

oncellchange

Fires when data changes at the data provider.

<applet>, <bdo>, <object>

Internet Explorer 5+

oncontextmenu

Fires when the user clicks the right mouse button to bring up the context-dependent menu.

Most elements

Internet Explorer 5+, Mozilla-based browsers

oncontrolselect

When using design mode or
the contenteditable feature, fires when the user selects
the object.

Most elements

Internet Explorer 5.5+

oncopy

Fires on target when selected content is copied from the document to the clipboard.

<a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <caption>, <center>, <cite>, <code>, <dd>, <dfn>, <dir>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> – <h6>, <hr>, <i>, <img>, <legend>, <li>, <listing>, <menu>, <nobr>, <ol>, <p>, <plaintext>, <pre>, <s>, <samp>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <td>, <th>, <tr>, <tt>, <u>, <ul>

Internet Explorer 5+

oncut

Fires when selected content
is cut from the document and added to system clipboard.

<a>, <address>, <applet>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <center>, <cite>, <code>, <dd>, <dfn>, <dir>, <div>, <dl>, <dt>, <em>, <embed>, <fieldset>, <font>, <form>, <h1> – <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <listing>, <map>, <marquee>, <menu>, <nobr>, <ol>, <p>, <plaintext>, <pre>,
<rt>, <ruby>, <s>, <samp>, <select>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <u>, <ul>, <var>, <xmp>

Internet Explorer 5+

ondataavailable

Fires when data arrives from data sources that transmit information asynchronously.

<applet>, <object>

Internet Explorer 4+

ondatasetchanged

Triggered when the initial
data is made available
from the data source or
when the data changes.

<applet>, <object>

Internet Explorer 4+

ondatasetcomplete

Indicates that all the data is available from the data source.

<applet>, <object>

Internet Explorer 4+

ondrag

Fires continuously on an object being dragged

Most elements

Internet Explorer 5+

ondragdrop

Triggered when the user drags an object onto the browser window to attempt to load it.

<body>, <frameset> (window)

Netscape 4–4.7

ondragend

Fires on object being dragged when the user releases the mouse button at the end of
a drag operation.

Most elements

Internet Explorer 5+

ondragenter

Fires on a valid drop target when the user drags an object over it.

Most elements

Internet Explorer 5+

ondragleave

Fires on a valid drop target when the user drags an object away from it.

Most elements

Internet Explorer 5+

ondragover

Fires continuously on a valid drop target while the user drags an object over it.

Most elements

Internet Explorer 5+

ondragstart

Fires when the user begins to drag a highlighted selection.

<a>, <acronym>, <address>, <applet>, <area>, <b>, <big>, <blockquote>, <body> (document), <button>, <caption>, <center>, <cite>, <code>, <dd>, <del>, <dfn>, <dir>, <div>, <dl>, <dt>, <em>, <font>, <form>, <frameset> (document), <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <hr>, <i>, <img>, <input> <bd>, <label>, <li>, <listing>, <map>, <marquee>, <menu>, <object>, <ol>, <option>, <p>, <plaintext>, <pre>, <q>, <s>, <samp>, <select>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <u>, <ul>, <var>, <xmp>

Internet Explorer 4+

ondrop

Fires on a valid drop target when the user drags an object onto it and releases the
mouse button.

Most elements

Internet Explorer 5+

onerror

Fires when the loading of a document or the execution of
a script causes an error. Used to trap runtime errors.

<body>, <frameset> (window), <img> (as well as <link>, <object>, <script>, <style> in Internet Explorer 4)

Netscape 3, 4–4.7
Internet Explorer 4+

onerrorupdate

Fires if a data transfer has been canceled by the onbeforeupdate event handler.

<a>, <applet>, <object>, <select>, <textarea>

Internet Explorer 4+

onfilterchange

Fires when a page CSS filter changes state or finishes.

Most elements

Internet Explorer 4+

onfinish

Triggered when a looping marquee finishes.

<marquee>

Internet Explorer 4+

onfocusin

Fires just before the element receives focus.

Most elements

Internet Explorer 6+

onfocusout

Fires just before the element loses focus.

Most elements

Internet Explorer 6+

onhelp

Triggered when the user presses the F1 key or similar help button in the user agent.

Most elements

Internet Explorer 4+

onlayoutcomplete

Fires when the layout area has been prepared for printing or print preview.

<base>, <basefont>, <bgsound>, <br>, <col>, <dd>, <div>, <dl>, <dt>, <font>, <head>, <hr>, <html>, <layoutrect>, <li>, <meta>, <ol>, <option>, <p>, <title>, <ul>

Internet Explorer 6

onlosecapture

Fires when the element loses mouse capture (IE enables an element to receive events for all mouse events, even if they don't occur at that element).

Most elements

Internet Explorer 5+

onmouseenter

Fires when the user moves the mouse over the element (different from onmouseover only in its bubbling behavior).

Most elements

Internet Explorer 5.5+

onmouseleave

Fires when the user moves the mouse away from the element (different from onmouseout only in its bubbling behavior).

Most elements

Internet Explorer 5.5+

onmousewheel

Fires when the mouse wheel is rotated by the user.

Most elements

Internet Explorer 6

onmove

Triggered when the user moves the window.

<body>, <frameset>

Netscape 4–4.7

onmove

Fires when the object moves
on screen.

Most display elements.

Internet Explorer 5.5+

onmoveend

Fires just after an object has finished moving on screen.

Most display elements.

Internet Explorer 5.5+

onmovestart

Fires just before an object is about to move on screen.

Most display elements.

Internet Explorer 5.5+

onpaste

Fires when content is pasted into the document.

<a>, <address>, <applet>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <center>, <cite>, <code>, <dd>, <dfn>, <dir>, <div>, <dl>, <dt>, <em>, <embed>, <fieldset>, <font>, <form>, <h1> – <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <listing>, <map>, <marquee>, <menu>, <nobr>, <ol>, <p>, <plaintext>, <pre>,
<rt>, <ruby>, <s>, <samp>, <select>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <u>, <ul>, <var>, <xmp>

Internet Explorer 5+

onpropertychange

Fires whenever a property of the element (or one of its contained objects, for example, its style object) changes.

Most elements.

Internet Explorer 5+

onreadystatechange

Similar to onload. Fires whenever the ready state for
an object has changed.

<applet>, <body>, <embed>, <frame>, <frameset>, <iframe>, <img>, <link>, <object>, <script>, <style>

Internet Explorer 4+

onresize

Triggered whenever an object is resized. Can only be bound to the window under Netscape via the <body> tag.

<applet>, <body>, <button>, <caption>, <div>, <embed>, <frameset>, <hr>, <img>, <marquee>, <object>, <select>,
<table>, <td>, <textarea>, <tr>

Netscape 4, 4.5 (supports <body> only); Internet Explorer 4+

onresizeend

When using design mode or the contenteditable feature, fires after the user finishing resizing an object.

Most elements

Internet Explorer 5.5+

onresizestart

When using design mode or the contenteditable feature, fires when the user begins resizing an object.

Most elements.

Internet Explorer 5.5+

onrowenter

Indicates that a bound data row has changed and new data values are available.

<applet>, <body>, <button>, <caption>, <div>, <embed>,
<hr>, <img>, <marquee>, <object>, <select>, <table>, <td>, <textarea>, <tr>

Internet Explorer 4+

onrowexit

Fires just prior to a bound data source control changing the current row.

<applet>, <body>, <button>, <caption>, <div>, <embed>,
<hr>, <img>, <marquee>, <object>, <select>, <table>, <td>, <textarea>, <tr>

Internet Explorer 4+

onrowsdelete

Fires just before rows are deleted from a recordset.

<applet>, <object>, <xml>

Internet Explorer 5+

onrowsinserted

Fires just after rows are added to a recordset.

<applet>, <object>, <xml>

Internet Explorer 5+

onscroll

Fires when a scrolling element is repositioned.

<body>, <div>, <fieldset>, <img>, <marquee>, <span>, <textarea>

Internet Explorer 4+

onselectionchange

Fires when the selection state of the document changes.

Document object

Internet Explorer 5.5+

onselectstart

Fires when the user begins
to select information by highlighting.

Nearly all elements.

Internet Explorer 4+

onstart

Fires when a looped marquee begins or starts over.

<marquee>

Internet Explorer 4+

onstop

Fires when the user clicks
the browser's Stop button,
or leaves the Web page

Document object

Internet Explorer 5+

Non-standard Event Binding in (X)HTML

Some browsers—Internet Explorer, most notably—permit you to bind events to objects in non-standard ways. The most common syntax is using a <<script>> tag with a for attribute indicating the id of the element to which the script should be bound, and the event attribute indicating the handler. For example:

<<p id="myParagraph">>Mouse over this text!<</p>>
<<script type="text/jscript" for="myParagraph" event="onmouseover">>
alert("Non-standard markup is a burden for developers and users alike!");
<</script>>

Unfortunately, this syntax is not a part of any HTML or XHTML standard, and browser support outside of Internet Explorer is spotty at best. For these reasons, developers should definitely stay away from this syntax; we’ve discussed it here so you can educate your co-workers in case you see it in use.

Note 

Curiously, while the for and event attributes aren’t supported in (X)HTML, they are supported in the DOM1 standard (as the htmlFor and event properties of an HTMLScriptElement). Nevertheless, avoid using them.

Binding Event Handler Attributes with JavaScript

While you can bind event handlers to parts of a document using (X)HTML event attributes,

it is sometimes convenient to use JavaScript instead, especially if you wish to add or remove handlers dynamically. Further, doing so tends to improve the separation between the structure of the document and its logic and presentation.

To use JavaScript for this task, it is important to understand that event handlers are accessed as methods of the objects to which they are bound. For example, to set the click handler of a form button, you set its onclick property to the desired code:

<<form action="#" method="get" name="myForm" id="myForm">>
<<input name="myButton" id="myButton" type="button" value="Click me" />>
<</form>>
<<script type="text/javascript">>
<<!--
document.myForm.myButton.onclick = new Function("alert('Thanks for
clicking! ')");
//-->>
<</script>>
Note 

As we’ve mentioned, the names of event handlers in JavaScript are always all lowercase. This marks one of the few exceptions to the rule that JavaScript properties are named using the “camel-back” convention (and reflects XHTML’s requirement for lowercased attributes as well).

Of course, you do not have to use an anonymous function when setting a handler. For example, notice here how we set a mouseover handler to an existing function:

<<script type="text/javascript">>
<<!--
function showMessage() 
{
  alert("Ouch! Get off me!");
}
//-->>
<</script>>
<<form action="#" method="get" name="myForm" id="myForm">>
<<button id="myButton">>Mouse over me!<</button>>

<<script type="text/javascript">>
<<!--
document.getElementById("myButton").onmouseover = showMessage;
//-->>
<</script>>
<</form>>

Regardless of how the function used is defined, you must make sure to register the event handler after the HTML element has been added to the DOM. Otherwise, you’ll cause a runtime error by trying to set a property (an event handler) of a non-existent object. One way to ensure this is to assign handlers after the document’s onload handler fires. Another way to ensure this condition is to place the script that assigns the handler after the element in question.

Event Handler Scope

As we discussed in Chapter 9, a script’s execution context is normally the Window in which the script’s text is found. However, script included in the text of an event handler has the context of the object to which it is bound. Instead of this pointing to the Window, this points to the object representing the element. Given the following script,

<<script type="text/javascript">>
<<!-- 
window.name = "My Window";
//-->>
<</script>>
<<p name="My Paragraph" onmouseover="alert(this.name);">>
Mouse Over me!
<</p>>

mousing over the paragraph results in the following dialog:

If your handlers are defined within <<script>>s and need access to the element at which the event occurs, simply pass them the this value from the handler as we saw in the previous example. In Netscape 4+, Internet Explorer 4+, and standards-supported browsers you can also use properties of the Event object to access this information. We’ll discuss how to do so in the later sections on the proprietary and DOM2 event models.

Note 

The fact that handlers have the context of the object to which they are bound explains why all form field objects have a form property: Given a reference to the field at which an event occurs, it allows you to quickly access the enclosing form.

An important subtlety is that it is only the JavaScript found in the text of the event handler attribute that has this scope; any JavaScript it calls has the “normal” scope. For example:

<<script type="text/javascript">>
<<!--
window.name = "My Window";
function showThisName() 
{
  alert(this.name);
}
//-->>
<</script>>
<<p name="My Paragraph" onmouseover="showThisName();">>
Mouse Over me!<</p>>

The result is

Return Values

One of the most useful features of event handlers is that their return values can affect the default behavior of the event. The default behavior is what would normally happen when the event occurs if left unhandled. For example, the default behavior of a click on a link is to load the link target in the browser. The default behavior of activating a Submit button is the submission of the form. The default behavior of a Reset button is to clear form fields, and so on.

To cancel the default behavior of an event, simply return false from its event handler. So when a submit handler for a form returns false, the form submission is canceled. Similarly, returning false in a click handler for a link prevents the browser from loading the target. Table 11-4 lists some useful events and the effects of their return values.

Table 11-4: Effect of Returning false from Important Event Handlers

Event Handler

Effect of Returning false

click

Radio buttons and checkboxes are not set. For Submit buttons, form submission is canceled. For Reset buttons, the form is not reset. For links, the link is not followed.

dragdrop

Drag and drop is canceled.

keydown

Cancels the keypress events that follow (while the user holds the key down).

keypress

Cancels the keypress event.

mousedown

Cancels the default action (beginning of a drag, beginning selection mode, or arming a link).

mouseover

Causes any change made to the window's status or defaultStatus properties to be ignored by the browser. (Conversely, returning true causes any change in the window's status to be reflected by the browser).

submit

Cancels form submission.

An example will make the utility of this capability more clear. Consider the following handler that confirms the user’s desire to follow the link:

<<a href="/" onclick="return confirm('Proceed to
 W3C?');">>W3C<</a>>

When a user clicks the link, the element’s click handler fires and prompts the user with a confirmation box. If the user response is positive (“Yes”), confirm() returns true, this value is returned by the handler, and the browser is allowed to proceed. If the user response is negative, confirm() returns false, this value is returned by the handler, and the default action of loading the URL is canceled.

The most common programming mistake when using this capability is to forget to return the value from the handler. If the previous example had instead been

<<a href="/" onclick="confirm('Proceed to W3C?');">>W3C<</a>>

then it wouldn’t matter how the user responded; the value of the confirm() would never be returned to the browser.

One of the most useful applications of event handler return values is in form submission. It is often desirable to validate form data before they are sent to the server in order to catch common typos or invalid data. Consider the following example that validates a single field:

<<script type="text/javascript">>
<<!--
function validateField(field)
{
  if (field.value == "")
  {
    alert("You must enter a user name.");
    field.focus();
    return false;
  }

  return true;
}
//-->>
<</script>>
<<form action="/cgi-bin/login.cgi" method="get"
      onsubmit="return validateField(this.username);">>
Username: <<input type="text" name="username" id="username" />>
<<input type="submit" value="Log in" />>
<</form>>

The event handler is passed a reference to a field in the current form and checks the contents of the username. If the field is empty, an error message is displayed, then a focus event is fired to bring the user back to the empty field, and finally false is returned to kill the form submission. If a value is provided, a value of true is returned, allowing the form submission to continue.

The previous example was used only to illustrate event handlers, return values, and event methods all working together. We’ll see many more complex form validation examples in Chapter 14.

Firing Events Manually

You can also invoke events directly on certain objects with JavaScript. Doing so causes the default action for the event to occur. For example:

<<form id="myForm" name="myForm" action="#" method="get">>
<<input type="button" id="button1" name="button1" value="Press Me"
onclick="alert('Hey there');" />>
<</form>>

<<script type="text/javascript">> 
<<!--
document.myForm.button1.click();
//-->>
<</script>>

This script fires a click on the button automatically triggering an alert.

Event handlers bound via (X)HTML attributes or explicitly with JavaScript are generally available to scripts in modern browsers just like any other method of the object. For example:

<<img name="myButton" id="myButton" alt="button"
     src="imageoff.gif" 
     onmouseover="this.src='imageon.gif';" 
     onmouseout="this.src='imageoff.gif';" />>
<<form action="#" method="get">>
<<input type="button" value="Fire Mouseover Handler"              
       onclick="document.images['myButton'].onmouseover();" />>
<<input type="button" value="Fire Mouseout Handler" 
       onclick="document.images['myButton'].onmouseout();" />>
<</form>>

The events and the elements on which they can be directly invoked are shown in Table 11-5. Some browsers might support more events, but those listed in Table 11-5 are the minimum that you will typically encounter.

Table 11-5: Events That Can Be Invoked Directly on (X)HTML Elements

Event Method

Elements

click()

<input type="button">, <input type="checkbox">, <input type="reset">, <input type="submit">, <input type="radio">, <a> (not in DOM, though commonly supported)

Blur()

<select>, <input>, <textarea>, <a>

focus()

<select>, <input>, <textarea>, <a>

select()

<input type="text">, <input type="password">, <input type="file">, <textarea>

submit()

<form>

reset()

<form>

One major pitfall when invoking events directly on forms is that the submit() method does not invoke the form’s onsubmit handler before submission. In the following example, both the alerts will be shown:

<<form name="myForm" id="myForm" action="somecgi.cgi" method="get"
      onsubmit="alert('onsubmit fired'); return false;">>
<<input name="mySubmit" id="mySubmit"
       type="submit" value="Submit" onclick="alert('click fired');" />>
<</form>>
<<script type="text/javascript">> 
<<!--
document.forms["myForm"].mySubmit.click();
//-->>
<</script>>

However, using the submit() method bypasses the onsubmit handler like so,

document.forms["myForm"].submit();

and causes the form to be sent to the server immediately. To address this, if you are going to submit a form programmatically you should fire any event handling code yourself.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Debugger     JavaScript Editor


©

R7