For example the onClick handler will handle the click event, the onSubmit handler will handle the submit event, and so on.. If the user clicks a button, for example, Java-Script might
Trang 1455
chapter
13
Handling Events
13.1 Introduction to Event Handlers
JavaScript reacts to events We have been talking about events since Chapter 1,
“Intro-duction to JavaScript,” because events are inherently part of almost all Web pages and
they make the pages interactive and dynamic JavaScript events are asynchronous,
meaning that they can happen at any time They are actions that are initiated by a user
visiting a Web page; for example, if the user submits a form or moves the mouse over a
link or an image, he or she might trigger an event When an event occurs, your browser
has some default actions it takes; for example, if you click on a link, it opens up the
loca-tion in the href JavaScript can also respond to a user’s acloca-tion and execute code in
response The event itself may be blur, click, change, keystroke, and so on We have seen
many examples using event handlers in previous examples This chapter explains how
each of the event handlers responds when events occur on different objects
JavaScript has three event models for programming events: the inline model, the
scripting model, and the DOM 2 model In this chapter we discuss the inline model and
the scripting model In Chapter 15, “The W3C DOM and JavaScript,” we describe the
way events are handled by the W3C DOM Level 2 model and its pros and cons
13.2 The Inline Model for Handling Events
This is the oldest and easiest way to handle events With the inline model, the event
han-dlers are attributes of an HTML tag and are used to handle the event for which they are
named For example the onClick handler will handle the click event, the onSubmit handler
will handle the submit event, and so on Although a very popular way of dealing with
events, the disadvantage of using the inline model is that JavaScript is intrusive; that is, it
is not separated from the HTML markup The inline model will be used here to show you
what the many event handlers do, and how they affect the objects in a document Later in
this chapter, we discuss the JavaScript scripting method for handling events
Trang 2As shown in previous examples, if the user clicks the submit button, JavaScript can
check to see if a form was filled out properly; or if the mouse moves over a link,
Java-Script can replace one image with a new one JavaJava-Script’s response to one of these
user-initiated events is called event handling If the user clicks a button, for example,
Java-Script might handle the event by calling a function that will perform some designated
task, such as to open a new window or bring a window into focus, perform a
calcula-tion, or submit a fillout form Here is a list of some of the kinds of events that
Java-Script can handle:
• Mouse actions
• Keyboard actions
• Actions on form fields
• When the page is first loaded or unloaded
• After a specified time has passed
• When an error has occurred
13.2.1 HTML and the Event Handler
JavaScript event handlers are not enclosed between <script></script> tags Event
han-dlers are attributes of HTML tags (specified in the HTML 4 specification) If the event is
associated with a form tag, then it will be an attribute of the <form> tag, and if associated
with a link, it will be an attribute of the <a href> tag, and so on Once you have decided
what event you want to handle, you normally assign a function to the event handler
This is called registering the event
To register an event, a string representing a command is assigned to the event handler
The command, usually a JavaScript function, will be executed when the event is
trig-gered by the user Whereas a property or method might be associated with a single
object, events are usually associated with more than one object The onClick event
han-dler, for example, may be associated with a form’s input tag, but it could also be
associ-ated with a link tag, or an image map area, or a simple button There is an order in which
events are handled See the section “Capturing and Bubbling (Trickle Down and Bubble
Up)” on page 500
(Note the spelling convention used for the event handlers The first word, on, is all
lowercase, and the first letter of each subsequent word is capitalized Unless the event is
being used as a method in a JavaScript program (see the section “JavaScript Object
Meth-ods and Events” on page 462), it is not case sensitive Using onClick or onclick is fine.)
Consider the following example:
<form>
<input type="button"
value="Wake me"
onClick="wakeUpCall()" />
</form>
Trang 3The HTML <form> tag contains an input tag with three attributes: type, value, and
onClick The input type is a “button”; it has a value of “Wake me”, and a JavaScript event
handler called onClick The onClick event handler is assigned a function called
“wake-UpCall()” When the user clicks the button labeled Wake me, a click event occurs, the
onClick event handler is triggered, and the wakeUpCall() function will be executed, as
demonstrated in Example 13.1 and shown in Figure 13.1
E X A M P L E 1 3 1
<html>
<head><title>Wake up call</title>
1 <script type="text/javascript">
3 setTimeout('alert("Time to get up!")',5000);
}
4 </script>
5 </head>
<body bgcolor="lightblue">
6 <form>
7 <input type="button"
8 value="Wake me"
9 onClick="wakeUpCall()">
</form>
</body>
</html>
E X P L A N A T I O N
1 The start of the JavaScript program
2 The wakeUpCall() function is defined in the JavaScript program, between the
<script></script> tags When the user clicks the form button, the function assigned
to the event handler is called; that is, wakeUpCall() is called The function itself is
defined in a JavaScript program, even though it is called from outside the program
3 The timer is set for 5,000 milliseconds The alert dialog box will pop up on the
screen 5 seconds after the user clicks the button
4 End of the JavaScript program
5 End of the HTML <head> tag.
6 This is the start of an HTML <form> tag.
7 The type of form uses a “button” input type.
8 The value is shown in the button as the text, “Wake me”.
9 The onClick event is assigned the name of a function When the user clicks the
button, the onClick event handler, wakeUpCall(), will be called.
Trang 4A list of JavaScript event handlers and their uses is given in Table 13.1
Figure 13.1 Before clicking the button (left); after clicking and waiting five seconds
(right).
Table 13.1 JavaScript Event Handlers and What They Do
onAbort Images When image loading has been interrupted.
onBlur Windows, frames,
all form objects
When focus moves out of this object except
hidden; e.g., when the cursor leaves a textbox.
onChange Input, select, and text areas When a user changes the value of an element
and it loses the input focus Used for form validation.
onClick Links, buttons, form objects,
image map areas
When a user clicks on an object Return false
to cancel default action
onDblClick Links, buttons, form objects When a user double-clicks on an object.
onDragDrop Windows When a user drops an object, such as a file,
onto the browser window.
onError Script When an error in the script occurs; e.g., a
syntax error.
onFocus Windows, frames,
all form objects
When a mouse is clicked or moved in a window or frame and it gets focus; except
hidden.
onKeyDown Documents, images, links, forms When a key is pressed.
onKeyPress Documents, images, links, forms When a key is pressed and released.
onKeyUp Documents, images, links, forms When a key is released.
onLoad Body, framesets, images After the document or image is loaded.
onMouseOut Links (and images within links) When the mouse moves away from a link.
Trang 513.2.2 Setting Up an Event Handler
There are two parts to setting up an event handler:
1 The event handler is assigned as an attribute of an HTML tag such as a document,
form, image, or link If you want the event to affect a document, then it would
become an attribute of the <body> tag; if you want the event to affect a button, then it would become an attribute of the form’s <input> tag; and if you want the event to affect a link, then it would become an attribute of the <a href> tag For
example, if the event is to be activated when a document has finished loading, the
onLoad event handler is used, and if the event happens when the user clicks an input device, such as a button, the onClick event handler is fired up.
<body onLoad="alert('Welcome to my Web site');">
<form>
<input type="button"
value="Tickle me "
onClick="alert('Hee hee ho hee');" />
</form>
</body>
2 The next step is to register or assign a value to the event handler The value can
be a built-in method such as alert() or confirm(), a user-defined function, or a
string of JavaScript statements Although the event handler is an attribute of an HTML tag, if a user-defined function is assigned to the event handler, then that function must be defined either in a JavaScript program or as direct script state-ments (separated by semicolons)
onMouseOver Links (and images within links) When the mouse moves over a link Return
true to prevent link from showing in the status bar.
onMove Windows When the browser window is moved.
onReset Forms reset button When the form’s Reset button is clicked
Return false to stop reset.
onResize Windows When the browser window changes size.
onSelect Form elements When a form element is selected.
onSubmit Forms When you want to send a form to the server
Return false to stop submission to the server
onUnload Body, framesets After the document or frameset is closed or
reset.
Table 13.1 JavaScript Event Handlers and What They Do (continued)
Trang 6And be careful with quotes! The handling function must be enclosed within either
double or single quotes If you have double quotes within the function, surround the
whole thing in single quotes, and if you have single quotes within the function, either
escape the single quote with a backslash, or surround the whole thing in double quotes
built-in method > onClick="window.open('myhome.html', 'newWin')"
user-defined function > onUnLoad="timeOver();"
group of statements > onChange="if (!checkVal(this.value, 1, 10)){
this.focus(); this.select();}"
E X A M P L E 1 3 2
<html>
<head><title>An event</title></head>
1 <body bgcolor="magenta" onUnload="alert('So long, stranger!')";>
<center>
2 <form>
3 <input type="button"
4 value="Click here to be alerted"
earth!")' />
6 </form>
</center>
</body>
</html>
E X P L A N A T I O N
1 The <body> tag contains the onUnload event handler When the user browses to
another page or exits the page, the alert() method will be triggered Normally you
would use this event for a quick cleanup or exit function, such as closing a
win-dow or clearing a page Starting some time-consuming process at this point would
be annoying to the user, because he or she is trying to leave this page without silly
delays The only purpose for this example is to demonstrate when the event
hap-pens
2 The form starts here with the <form> tag
3 The input type for this form is “button”.
4 The value on the button is “Click here to be alerted”.
5 The onClick event is an attribute of the HTML form’s input tag When the user
clicks the mouse on the button (the onClick event), the alert() method is called
See Figure 13.2
6 The HTML form tag ends here
Trang 713.2.3 Return Values
Sometimes the event handler’s return value is necessary if a certain action is to proceed
The browser’s default actions can be suppressed by returning a false value, or a form’s
sub-mission can be completed by sending back a true value For example, if the onSubmit
han-dler gets a true value back from a function or method, then a form may be submitted to
the server, and if not, the form will be stopped In Chapter 11, “Working with Forms and
Input Devices,” we saw that when validating a form, return values are used Example 13.3
illustrates these return values
Figure 13.2 When the user clicks the button, the onClick event is activated (left);
when the page is refreshed or exits, the onUnload event is activated (right).
E X A M P L E 1 3 3
<html>
<head><title>An HTML Form and the onSubmit Event Handler</title>
<script type="text/javascript">
2 if(yourinfo.namestring.value == "" ||
yourinfo.namestring.value == null){
// Check for an empty string or null value
3 alert("Please type in your name");
} else{
} }
</script>
</head>
<body><big>
<b>
6 <form name="info" action="/cgi-bin/bookstuff/form1.cgi"
method="post"
7 onSubmit="return checkForm(document.info)">
<br /><br />
Continues
Trang 813.2.4 JavaScript Object Methods and Events
JavaScript event methods can be used to simulate the event attributes (See the section
“Unobtrusive JavaScript” in Chapter 15.) An event handler is an attribute of an HTML
Type your name here:
8 <input type="text" name="namestring" size="50" />
<br /><br />
9 <input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</form>
<big>
</body>
</html>
E X P L A N A T I O N
1 The function called checkForm() has one argument, yourinfo, which is a reference
to the form defined on line 6
2 If the user didn’t enter anything into the textbox, the value of the input type will
be null The expression if(yourinfo.namestring.value == “”) checks for an empty
field
3 The user didn’t enter anything into the textbox An alert dialog box will appear
on the screen, and after the user clicks OK, he or she will have a chance to fill out
the form again
4 If false is returned from this function, the form will not be submitted to the server.
5 If true is returned from this function, the form will be submitted to the server.
6 The HTML form starts here The form, document.forms[0], is named “info” The
action attribute contains the URL of the program that will process the form, a CGI
script on the server The method attribute defines the HTTP method that
deter-mines how the data will be sent to the server
7 The onSubmit event handler is an attribute of the HTML <form> tag and is
trig-gered when the user clicks the submit button The event handler is a function
called checkForm() Its parameter is the name of the form, document.info (also
could use its array name: document.forms[0]) The return keyword is required
when using the onSubmit event handler One of two values will be returned: either
true or false.
8 The input type for this form is a text field box Its name is “namestring” and it can
hold a string of up to 50 characters
9 The input type is the submit button When the user clicks this button, the
onSub-mit event handler on line 7 is activated See Figure 13.3.
E X A M P L E 1 3 3 (C O N T I N U E D)
Trang 9tag, whereas an event method is applied to an object Because HTML elements are also
treated as objects (e.g., the window, form, or button are also JavaScript objects), there
are several methods that can be applied to these objects to simulate events (see
Table 13.2) When an object uses an event method, the method behaves as though the
event has happened; for example, the click() method behaves like the onClick event, the
blur() method behaves like the onBlur event, and so on.1 The event method is applied to
the object with the dot syntax, as are all other methods; for example, in a JavaScript
pro-gram you might see something like the following:
document.test.button1.click(), window.focus(), document.myform.submit();
Figure 13.3 Using the onSubmit event and return values If the return value is true
the form is submitted; otherwise, it is stopped.
1 Event methods behave as though the event has happened but in themselves do not trigger an event
handler For example, the click() method does not trigger the onClick event handler.
Table 13.2 Event Object Methods
Event
Method
Event Handler It
blur() onBlur Removes focus from windows, frames, form fields.
click() onClick Simulates a mouse click in form fields (buttons).
focus() onFocus Puts focus in a window, frame, form field.
reset() onReset Clears the form fields.
select() onSelect Selects or highlights text in a form field.
submit() onSubmit Submits a form.
Trang 10E X A M P L E 1 3 4
<html>
<head><title>Simulation Methods</title></head>
<body bgcolor="yellow">
1 <form name="myform"
2 action="http://localhost/cgi-bin/doit.pl"
method="post">
Enter your name:<br />
<input type="text"
name="namefield"
id="namefield"
size="30"
value="Name: "
3 onFocus="this.select()" />
<p>
Enter your address:<br />
4 <input type="text"
name="addressfield"
id="namefield"
size="30"
value="Address: "
5 onFocus="this.select()" />
</p><p>
</form>
6 <a href="#" onClick="JavaScript: document.myform.submit();">
Click here to submit your form</a>
</p><p>
7 <a href="#" onClick="JavaScript:document.myform.reset();">
Click here to reset your form</a>
</p>
</body>
</html>
E X P L A N A T I O N
1 A form named myform is started.
2 This is the URL where the form will be processed after it is submitted
3 The onFocus event handler is assigned an event method called select() For this
textbox, when the mouse cursor is clicked in the box, the onFocus event is
trig-gered and the event is handled by highlighting or selecting the text in the box
4 Another textbox is defined to hold the user’s address
5 When the cursor is moved into this field, the textbox gets focus and the select()
method is called to highlight this box, as in line 3
6 A deactivated link is assigned an onClick event handler When the user clicks the
link, the JavaScript code is executed The pseudo JavaScript: protocol is followed
by a reference to the form and a submit() method, which causes the form to be
submitted when the user clicks the link A JavaScript function could also have