Table 10.1 JavaScript event handlers
focus
event is onFocus
.
To create an event handler for an HTML tag, add an event handler attribute to the tag. Put JavaScript code in quotation marks as the attribute value. The general syntax is
<TAG eventHandler="JavaScript Code">where
TAG
is an HTML tag, eventHandler
is the name of the event handler, and JavaScript Code
is a sequence of JavaScript statements.
For example, suppose you have created a JavaScript function called compute
. You make Navigator call this function when the user clicks a button by assigning the function call to the button's onClick
event handler:
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">You can put any JavaScript statements as the value of the
onClick
attribute. These statements are executed when the user clicks the button. To include more than one statement, separate statements with semicolons (;).
Notice that in the preceding example, this.form
refers to the current form. The keyword this
refers to the current object, which in this case is the button. The construct this.form
then refers to the form containing the button. The onClick
event handler is a call to the compute
function, with the current form as the argument.
When you create an event handler, the corresponding JavaScript object gets a property with the name of the event handler. This property allows you to access the object's event handler. For example, in the preceding example, JavaScript creates a Button
object with an onclick
property whose value is "compute(this.form)"
.
Be sure to alternate double quotation marks with single quotation marks. Because event handlers in HTML must be enclosed in quotation marks, you must use single quotation marks to delimit string arguments. For example:
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"In general, it is good practice to define functions for your event handlers instead of using multiple JavaScript statements:
onClick="window.open('mydoc.html', 'newWin')">
Figure 10.1 Form with an event handler
<HEAD>
<SCRIPT>
<!--- Hide script from old browsers
function compute(f) {
if (confirm("Are you sure?"))
f.result.value = eval(f.expr.value)
else
alert("Please come back again.")
}
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>The HEAD of the document defines a single function,
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
compute
, taking one argument, f
, which is a Form
object. The function uses the window.confirm
method to display a Confirm dialog box with OK and Cancel buttons.
If the user clicks OK, then confirm
returns true, and the value of the result
text field is set to the value of eval(f.expr.value)
. The JavaScript function eval
evaluates its argument, which can be any string representing any JavaScript expression or statements.
If the user clicks Cancel, then confirm
returns false and the alert
method displays another message.
The form contains a button with an onClick
event handler that calls the compute
function. When the user clicks the button, JavaScript calls compute
with the argument this.form
that denotes the current Form
object. In compute
, this form is referred to as the argument f
.
<SCRIPT LANGUAGE="JavaScript">
function fun1() {
...
}
function fun2() {
...
}
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton"
onClick="fun1()">
</FORM>
<SCRIPT>
document.myForm.myButton.onclick=fun2
</SCRIPT>
JavaScript 1.0. You cannot reset an event handler.
fun2
itself, not fun2()
(the latter calls fun2
and has whatever type and value fun2
returns).<INPUT onClick=fun1>
in the HTML source to make fun1
the onClick
handler for an input. Instead, you must set the value in JavaScript, as in the preceding example.myForm.onsubmit
or myButton.onclick
.
event
object. The event
object provides information about the event, such as the type of event and the location of the cursor at the time of the event. When an event occurs, and if an event handler has been written to handle the event, the event
object is sent as an argument to the event handler.
In the case of a MouseDown
event, for example, the event
object contains the type of event (in this case "MouseDown"
), the x and y position of the mouse cursor at the time of the event, a number representing the mouse button used, and a field containing the modifier keys (Control, Alt, Meta, or Shift) that were depressed at the time of the event. The properties of the event
object vary from one type of event to another, as described in the Client-Side JavaScript Reference.
JavaScript 1.1 and earlier versions.
The event
object is not available.
window
or document
object to handle certain types of events instead of leaving them for the individual parts of the document. For example, you may want the document
object to handle all MouseDown
events no matter where they occur in the document.
JavaScript's event capturing model allows you to define methods that capture and handle events before they reach their intended target. To accomplish this, the window
, document
, and layer
objects use these event-specific methods:
captureEvents
--captures events of the specified type.releaseEvents
--ignores the capturing of events of the specified type.routeEvent
--routes the captured event to a specified object.handleEvent
--handles the captured event (not a method of layer
).Click
events occurring in a window. Briefly, the steps for setting up event capturing are:
The following sections explain these steps.
Click
events, use a statement such as the following:
window.captureEvents(Event.CLICK);The argument to
captureEvents
is a property of the event
object and indicates the type of event to capture. To capture multiple events, the argument is a list separated by or (|
). For example, the following statement captures Click
, MouseDown
, and MouseUp
events:
window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP)
NOTE: If a window with frames needs to capture events in pages loaded from different locations, you need to usecaptureEvents
in a signed script and callenableExternalCapture
. For information on signed scripts, see Chapter 14, "JavaScript Security."
e
is the event
object for the event.
function clickHandler(e) {You have the following options for handling the event:
//What goes here depends on how you want to handle the event.
//This is described below.
}
function clickHandler(e) {This allows the event to be completely handled by the document or window. The event is not handled by any other object, such as a button in the document or a child frame of the window.
return true;
}
false
. In the case of a link, the link is not followed. If the event is non-cancelable, this ends the event handling for that event. function clickHandler(e) {This allows you to suppress the handling of an event type. The event is not handled by any other object, such as a button in the document or a child frame of the window. You can use this, for example, to suppress the right mouse button in an application.
return false;
}
routeEvent
. JavaScript looks for other event handlers for the event. If another object is attempting to capture the event (such as the document), JavaScript calls its event handler. If no other object is attempting to capture the event, JavaScript looks for an event handler for the event's original target (such as a button). The routeEvent
function returns the value returned by the event handler. The capturing object can look at this return and decide how to proceed. routeEvent
calls an event handler, the event handler is activated. If routeEvent
calls an event handler whose function is to display a new page, the action takes place without returning to the capturing object.function clickHandler(e) {
var retval = routeEvent(e);
if (retval == false) return false;
else return true;
}
handleEvent
method of an event receiver. Any object that can register event handlers is an event receiver. This method explicitly calls the event handler of the event receiver and bypasses the capturing hierarchy. For example, if you wanted all Click
events to go to the first link on the page, you could use: function clickHandler(e) {As long as the link has an
window.document.links[0].handleEvent(e);
}
onClick
handler, the link will handle any click event it receives.
window.onClick = clickHandler;
<HTML>
<SCRIPT>
function fun1(e) {
alert ("The window got an event of type: " + e.type +
" and will call routeEvent.");
window.routeEvent(e);
alert ("The window returned from routeEvent.");
return true;
}
function fun2(e) {
alert ("The document got an event of type: " + e.type);
return false;
}
function setWindowCapture() {
window.captureEvents(Event.CLICK);
}
function releaseWindowCapture() {
window.releaseEvents(Event.CLICK);
}
function setDocCapture() {
document.captureEvents(Event.CLICK);
}
function releaseDocCapture() {
document.releaseEvents(Event.CLICK);
}
window.onclick=fun1;
document.onclick=fun2;
</SCRIPT>
...
</HTML>
onChange
event handler on each form element that you want validated.onClick
event handler on the button that submits the form.<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function isaPosNum(s) {
return (parseInt(s) > 0)
}
function qty_check(item, min, max) {
var returnVal = false
if (!isaPosNum(item.value))
alert("Please enter a positive number")
else if (parseInt(item.value) < min)
alert("Please enter a " + item.name + " greater than " + min)
else if (parseInt(item.value) > max)
alert("Please enter a " + item.name + " less than " + max)
else
returnVal = true
return returnVal
}
function validateAndSubmit(theform) {
if (qty_check(theform.quantity, 0, 999)) {
alert("Order has been Submitted")
return true
}
else {
alert("Sorry, Order Cannot Be Submitted!")
return false
}
}
</SCRIPT>
</HEAD>
isaPosNum
is a simple function that returns true if its argument is a positive number, and false otherwise.
qty_check
takes three arguments: an object corresponding to the form element being validated (item
) and the minimum and maximum allowable values for the item (min
and max
). It checks that the value of item
is a number between min and max and displays an alert if it is not.
validateAndSubmit
takes a Form
object as its argument; it uses qty_check
to check the value of the form element and submits the form if the input value is valid. Otherwise, it displays an alert and does not submit the form.
qty_check
as an onChange
event handler for a text field and validateAndSubmit
as the onClick
event handler for a button.
<BODY>This form submits the values to a page in a server-side JavaScript application called
<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post">
How many widgets today?
<INPUT TYPE="text" NAME="quantity" onChange="qty_check(this, 0, 999)">
<BR>
<INPUT TYPE="button" VALUE="Enter Order" onClick="validateAndSubmit(this.form)">
</FORM>
</BODY>
lwapp.html
. It also could be used to submit the form to a CGI program. The form is shown in the following figure.
The onChange
event handler is triggered when you change the value in the text field and move focus from the field by either pressing the Tab key or clicking the mouse outside the field. Notice that both event handlers use this
to represent the current object: in the text field, it is used to pass the JavaScript object corresponding to the text field to qty_check
, and in the button it is used to pass the JavaScript Form
object to validateAndSubmit
.
To submit the form to the server-based program, this example uses a button that calls validateAndSubmit
, which submits the form using the submit
method, if the data are valid. You can also use a submit button (defined by <INPUT TYPE="submit">
) and then put an onSubmit
event handler on the form that returns false if the data are not valid. For example,
<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post"When
onSubmit="return qty_check(theform.quantity, 0, 999)">
...
<INPUT TYPE="submit">
...
</FORM>
qty_check
returns false if the data are invalid, the onSubmit
handler will prohibit the form from being submitted.
Last Updated: 05/27/99 21:21:34