Events
Many different types of events take place in browsers. JavaScript provides access to a number of events that would be useful to you, such as the click event, which occurs when the left mouse button is pressed once. Most of the events correspond to an HTML element that a user can see and manipulate such as a button or a check box. Table 3.6 contains a list of events that can be captured by JavaScript and the JavaScript object with which the event is associated.
Table 3.6 Browser Events
Event |
Object |
Occurs When... |
---|---|---|
Abort |
Image |
images do not finish loading |
Blur |
Button, Checkbox, FileUpload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window |
input focus is removed from the element |
Change |
FileUpload, Select, Text, Textarea |
value of the element is changed |
Click |
Area, Button Checkbox, Document, Link, Radio, Reset, Submit |
element is clicked |
DblClick |
Area, Document, Link |
mouse button is double-clicked |
DragDrop |
Window |
object is dropped onto browser Window |
Error |
Image, Window |
there is an error in the page or image |
Focus |
Button, Checkbox, FileUpload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window |
input focus is given to element |
KeyDown |
Document, Image, Link, Textarea |
key is depressed |
KeyPress |
Document, Image, Link, Textarea |
key pressed and held down |
KeyUp |
Document, Image, Link, Textarea |
key is released |
Load |
Document, Image, Layer, Window |
page is loaded into browser |
MouseDown |
Button, Document, Link |
left mouse button is depressed |
MouseMove |
Window |
mouse cursor is moved |
MouseOut |
Area, Layer, Link |
mouse cursor is moved out of the element's bounds |
MouseOver |
Area, Layer, Link |
mouse is moved over element |
MouseUp |
Button, Document, Link |
mouse button is released |
Move |
Frame |
element is moved |
Reset |
Form |
form is reset |
Resize |
Frame, Window |
browser window is resized |
Select |
Text, Textarea |
input field is selected |
Submit |
Form |
form is submitted |
Unload |
Window |
current page is unloaded |
Of the events covered in the previous table, the Error and Abort events deserve a little more explanation because they are not as straightforward as the rest.
The Error event is used by the Window and Image objects to indicate that an error occurred while either loading an HTML page or loading an image. This type of error will result in the browser issuing a JavaScript syntax error or a runtime error.
The Abort event is used by the Image object to indicate that the loading of an image was aborted. This type of event occurs often because users become impatient waiting for a large image to load, so they stop the image load before it completes by clicking the browser's Stop button or clicking a link to another page.
Event Handlers
Now that you know the types of events that JavaScript provides, access to them is just a matter of capturing those events. Events are captured using event handlers. By assigning a function or a single line of JavaScript code to an object's event handler, you can capture an event and take action. Table 3.7 shows all the event handlers and the events they are associated with.
Table 3.7 Event Handlers
Event |
Event Handler |
---|---|
Abort |
onAbort |
Blur |
onBlur |
Change |
onChange |
Click |
onClick |
DblClick |
onDblClick |
DragDrop |
onDragDrop |
Error |
onError |
Focus |
onFocus |
KeyDown |
onKeyDown |
KeyPress |
onKeyPress |
KeyUp |
onKeyUp |
Load |
onLoad |
MouseDown |
onMouseDown |
MouseMove |
onMouseMove |
MouseOut |
onMouseOut |
MouseOver |
onMouseOver |
MouseUp |
onMouseUp |
Move |
onMove |
Reset |
onReset |
Resize |
onResize |
Select |
onSelect |
Submit |
onSubmit |
Unload |
onUnload |
Capturing Events
Event handlers can be defined in one of two ways. The first and most common way is to define the handler inside HTML tags much in the same way HTML tag properties are assigned. For example, to display an alert box when a button is clicked, simply assign a JavaScript alert box to the onClick event handler inside the button's HTML tag as follows:
<form name="myForm"> <input type="button" name="myButton" value="Press Me" onClick="alert('myButton was pressed')"> </form>
Anytime myButton is clicked an alert box will be displayed that tells the user that "myButton was pressed". Remember that not all events are associated with every object. To see what events and event handlers are available to a particular object, look for the object in Chapter 8, "Client-Side."
The second way to define event handlers is to define the handler inside JavaScript code using dot notation. Listing 3.2 demonstrates how to assign a JavaScript alert box to the onClick event handler using dot notation.
Listing 3.2 Defining Event Handlers Using Dot Notation
<html> <form name="myForm"> <input type="button" name="myButton" value="Press Me"> </form> <script type="text/javascript" language="JavaScript"> <!-- document.myForm.myButton.onclick="alert('myButton was pressed')"; //--> </script> </html>
In listing 3.2 myButton was initially created using standard HTML tags. Directly after creating the button JavaScript dot notation is used to access the button object and assign an alert box to the onclick handler.
NOTE
Notice that in Listing 3.2 the onclick property was written using a lowercase c rather than an uppercase C as was used when accessing the onClick property via the HTML input tag. This is not a typo! When defining event handlers inside HTML, use the uppercase characters as shown in Table 3.7. When defining event handlers inside JavaScript code using dot notation, the event handlers must not contain any uppercase characters.
Canceling Events
One of the most common uses of event handlers is validation of data entered through an HTML form. For example you might want to verify that a password entered by a user in a password change form is valid before submitting the form to the server. If the password entered by the user is not valid, the user should be notified of the problem and the form should not be submitted. Utilizing the material covered so far, it is easy to capture the Click event of the form's submit button and alert the user of the problems with the password entered. But how do you prevent the event from continuing and the form from being submitted to the server? The Submit event can be canceled by simply returning false in the event handling routine. Listing 3.3 demonstrates how to cancel the form submission.
Listing 3.3 Canceling the Submit Event
<html> <script type="text/javascript" language="JavaScript"> <!-- function validatePassword() { passwd = document.passwordForm.password.value; //Password must be between 3 and 15 characters if((passwd.length < 3) || (passwd.length > 15)) { alert("Password must be less than 15 characters but greater than 3!"); return(false); } } //--> </script> <center> <h1>Password Change Page</h1> Please enter your user name and new password.<br> (Password must be between 3 and 15 characters.)<br><br> <form name="passwordForm" action="success.html" onSubmit="return validatePassword()"> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit"> </form> </html>
Not all the event handlers allow you to stop an event from taking place, but some do. Of the events that can be stopped, the value used to stop the event varies. Table 3.8 shows the events that acknowledge return codes and what values to return to cancel the event.
Table 3.8 Event Handler Return Values
Event |
Value to Return to Cancel Event |
---|---|
OnClick |
false |
OnKeyDown |
false |
OnKeyPress |
false |
OnMouseDown |
false |
OnMouseOver |
true (prevents URL from appearing in status bar) |
onMouseUp |
false |
onReset |
false |
onSubmit |
false |
Invoking Event Handlers
There are times when you might want to explicitly invoke a particular event handler even though no event took place. This is easy to accomplish because the event handlers are essentially pointers to functions stored as a property of an object that should be executed when a particular event occurs. To invoke an event handler, simply use dot notation to execute the event handler as if it were a function. For example, in the following piece of code, we want to alert the user about a sweepstakes when he moves his cursor over the Lamborghini link. We also want to remind him of the sweepstakes when he goes back to the previous page. To do this, the event handler for the Lamborghini link is executed when the user clicks the Previous Page link.
<a href="sweepstakes.html" onMouseOver="alert('Enter our sweepstakes for a chance to win a brand new sports car!')">Lamborghini</a><br> <a href="intro.html" onClick="document.links[0].onmouseover()">Previous Page</a>
Timers
Even though JavaScript does not directly provide an event-driven timer, we will discuss timers in this section because timers should generally be thought of in terms of events. Because JavaScript does not directly provide a timer, it is possible to use the Window object's setInterval() method to serve the same purpose.
NOTE
The setInterval() method is supported in JavaScript 1.2 and higher.
The setInterval() method repeatedly calls a function or evaluates an expression each time a time interval (in milliseconds) has expired. This method continues to execute until the window is destroyed or the clearInterval() method is called.
For example, in Listing 3.4 the setInterval() method is executed when the document opens and begins to call the dailyTask() function every 20,000 milliseconds. The dailyTask() function evaluates the time each time it is called, and when it is 8:00 a.m., the code within the if statement is called, alerting the user and then clearing the interval. When the clearInterval() method is called, setInterval() halts execution.
Listing 3.4 Creating a Timed Event with the setInterval() Method
<html> <script type="text/javascript" language="JavaSCript"> <!-- function dailyTask() { var today = new Date(); if ((today.getHours() == 8) && (today.getMinutes() == 0)) { alert("It is 8:00 a.m."); clearInterval(timerID); } } //Set interval to 20,000 milliseconds timerID = setInterval("dailyTask()",20000); //--> </script> </html>
As mentioned earlier the setInterval() method is only available in JavaScript 1.2 and higher. If you need to support an earlier version of JavaScript, you will have to use the setTimeout() method.
The setTimeout() method is usually used to evaluate an expression after a specific amount of time. Unlike the setInterval() method, the setTimeout() method is a one-time process that is not repeated an infinite number of times. Listing 3.5 produces the same result as Listing 3.4, using the setTimeout() method instead of the setInterval() method.
Listing 3.5 Creating a Timed Event with the setTimeout() Method
<html> <script type="text/javascript" language="JavaScript"> <!-- function dailyTask() { var today = new Date(); if ((today.getHours() == 8) && (today.getMinutes() == 0)) { alert("It is 8:00 a.m."); } } //Set delayed execution of function to 20,000 milliseconds setTimeout("dailyTask()",20000); //--> </script> </html>