12.1 Introduction to Event Handlers

We have been talking about events since Chapter 1, "Introduction 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 may trigger an event. [1] When an event occurs, JavaScript can execute code in response to the user's action. As shown in previous examples, if the user presses the submit button, JavaScript may check to see if a form was filled out properly; or if the mouse moves over a link, JavaScript may replace one image with a new one. JavaScript's response to one of these user-initiated events is called event handling . If the user presses a button, for example, JavaScript may 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 or submit a fillout form.

[1] An event is initiated by a user. The event itself may be blur, click, change, or the like. The event handler is the event preceded with " on ". For example, onBlur and onClick are attributes of an HTML tag, and are used to handle the event for which they are named.

JavaScript event handlers are not enclosed between <script></script> tags. Event handlers 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. The string that is assigned to the event handler is the command that will be executed when the event is triggered by the user. The command is a JavaScript built-in function or user-defined function. The function will be called when the event is triggered.

Whereas a property or method may be associated with a single object, events are usually associated with a collection of objects. The onClick event handler, for example, may be associated with a form's input tag, but it could also be associated with a link tag, or an image map area, or a simple button.

(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 "Event Handlers as JavaScript Methods" on page 356), it is not case sensitive. Using onClick or onclick are both fine.)

Consider the following example:

 <form><input type="button"             value="Wake me"             onClick="wakeupCall()"> </form> 

The 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 "wakeupCall()" . When the user clicks the button labeled Wake me! , the onClick event handler is triggered, and the wakeupCall() function will be executed, as demonstrated in Example 12.1 and shown in Figure 12.1.

Example 12.1
 <html>  <head>  <title>Wake up call</title> 1   <script language="javascript"> 2  function wakeupCall(){  //  Function is defined here  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>  
Figure 12.1. Before clicking the button (left); after clicking and waiting five seconds (right).



  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 five 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 presses the button, the onClick event handler, wakeupCall() , will be called.

A list of JavaScript event handlers and their uses is given in Table 12.1.

Table 12.1. JavaScript events and what they do.

Event Handler

What It Affects

When It Happens



When image loading has been interrupted .


Windows, frames , all form objects

When focus moves out of this object except hidden ; e.g., when the cursor leaves a text box.


Input, select, and text areas

When a user changes the value of an element and it loses the input focus. Used for form validation.


Links, buttons , form objects, image map areas

When a user clicks on an object. Return false to cancel default action.


Links, buttons, form objects

When a user double-clicks on an object.



When a user drops an object, such as a file, onto the browser window.



When an error in the script occurs; e.g., a syntax error.


Windows, frames, all form objects

When a mouse is clicked or moved in a window or frame and it gets focus; except hidden .


Documents, images, links, forms

When a key is pressed.


Documents, images, links, forms

When a key is pressed and released.


Documents, images, links, forms

When a key is released.


Body, framesets, images

After the document or image is loaded.


Links (and images within links)

When the mouse moves away from a link.


Links (and images within links)

When the mouse moves over a link. Return true to prevent link from showing in the status bar.



When the browser window is moved.


Forms reset button

When the forms reset button is clicked. Return false to stop reset.



When the browser window changes size.


Form elements

When a form element is selected.



When you want to send a form to the server. Return false to stop submission to the server.


Body, framesets

After the document or frameset is closed or reset.

12.1.1 Creating the 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, 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 on 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 assign a value to the event handler. The value may 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 statements (separated by semicolons).

And 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();}"  
Example 12.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" 5  onClick='alert("Watch out! An asteroid is approaching   earth!")'>  6   </form>     </center>     </body>     </html> 


  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 window or clearing a page. Starting some time-consuming process at this point would be annoying to the user, since he is trying to leave this page without silly delays. The only purpose for this example, is to demonstrate when the event happens.

  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 12.2.

    Figure 12.2. When the user presses the button, the onClick event is activated (left); when the page is refreshed or exits, the onUnload event is activated (right).


  6. The HTML form tag ends here. The output is shown in Figure 12.2.

JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net