1.4 JavaScript and Events

HTML is static. It can be used to create buttons and boxes and fillout forms, but it cannot by itself react to user input. Normally, the browser bundles up the form information and sends it off to a server to be handled. But JavaScript is not static; it is dynamic. It can interact asynchronously with users on the client side. For example, when a user fills out a form; presses a button, link, or image; or moves his mouse over a link, JavaScript can respond to the event and interact dynamically with the user. For example, JavaScript can examine user input and validate it before sending it off to a server, or cause a new image to appear if a mouse moves over a link or presses a button. Events are discussed in detail in Chapter 12, "Handling Events," but you should be made aware of them right at the beginning because they are inherently part of what JavaScript does, and there will be examples throughout this text that make use of them.

The events are tied to HTML. In the following example, an HTML form is created with the <form> tag and its attributes. Along with the type and value attributes, the JavaScript onClick event handler is just another attribute of the HTML <form> tag. The type of input box is called a "button" and the value assigned to the button is "Pinch me" . When the user clicks on the button in the browser window, a JavaScript event, called Click , will be triggered. The onClick event handler is assigned a value which is the command that will be executed after the button has been clicked. In our example, it will result in an alert being sent to the user, displaying " OUCH!! ". See the output of Example 1.1 in Figures 1.2 and 1.3.

Example 1.1
 <html>     <head><title>Event</title></head>     <body> 1      <form> 2         <input type ="button" 3                value = "Pinch me" 4  onClick="alert('OUCH!!')" >  5      </form>     </body>     </html> 
Figure 1.2. The onClick event is triggered when the button is pressed.


Figure 1.3. JavaScript handles the onClick event.


Some of the events that JavaScript can handle are listed in Table 1.1.

Table 1.1. JavaScript event handlers.

Event Handler

What Caused It


Image loading was interrupted .


The user moved away from a form element.


The user changed a value in a form element.


The user clicked on a button-like form element.


The program had an error when loading an image.


The user activated a form element.


The document finished loading.


The mouse moved away from an object.


The mouse moved over an object.


The user submitted a form.


The user left the window or frame.

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