Next: Introducing the Document Object Model |
The online chapter "Introduction to JavaScript" offered an explanation of JavaScript and all its basics. In this chapter, we'll focus on some tasks you can accomplish with JavaScript. In particular, you'll see the different ways that you can handle events that occur when people use your HTML documents and how you can react to those events with scripted responses.
After that, you'll see how to react to data that's been entered into HTML forms, calculate values based on that data, and return values to the user. You'll also see how to use JavaScript with full-fledged HTML forms to check for errors or trouble with input before those forms are submitted to CGI processing scripts.
Finally, we'll look at some other JavaScript automation possibilities, including automatic page redirection, launching new pages with JavaScript, and working with an HTML frames interface using a JavaScript control.
This chapter discusses the following:
What events are and how they are handled
Using object pointers and accessing objects from within functions
Using JavaScript and HTML forms for interaction with the user
Using JavaScript to check HTML form data for errors
Automating the browser with JavaScript to redirect pages, create special links, and manage HTML frames
In "Introduction to JavaScript", you saw numerous references to event handling. One of JavaScript's main functions is to react to what the user does on the page, whether that's selecting buttons, clicking hyperlinks, or even hovering over items with the mouse. Anything that the user does is considered an event, as is anything that happens automatically or that occurs within the browser. For instance, when a page loads, that's an event. When the page is unloaded so that another page can appear, that's an event, too.
To deal with these events, you'll need to add event handlers to certain XHTML elements. You'll follow this general format:
<element event_handler="JavaScript code or function call"> </element>
NOTE
Most <form> elements, hyperlinks, and some other elements can accept the various event handler attributes. For instance, a few of the event handlers are designed specifically to work with the <body> element, so that things can happen automatically when the page is first loaded into a browser window.
The <form> elements are where you'll see a lot of event handlers, however. Take the following example, which enables you to use a form button not to submit the form to a CGI script, but rather to submit the entry to a JavaScript function:
<h1>Computing the Entry:</h1> <form> Enter a number: <input type="text" name="userEntry" size="5" /> <br /> Here's the result: <input type="text" name="result" size="5" /> <br /> <input type="button" value="Calc" onclick="result.value = compute(userEntry)"> </form>
In this snippet of code, the user is asked to enter a number in the top form element (a text entry box) and then click the Calc button. When that button is clicked, an event handler, called onClick, is invoked. That event handler calls a function, called compute, and sends a pointer to the <input> object named userEntry so the function can find that data and use it for the calculation. Then, when the function returns a value, it's assigned to the variable result, and that result appears in the second entry box, which happens to be named result. You can see how all this looks in Figure 1. (Note that the function isn't shown in the preceding sample, but it simply adds 100 to the number.)
Figure 1 Using event handlers and form elements, JavaScript can return values without worrying about CGI scripts.
Sometimes called intrinsic events to suggest that they're scripting attributes without the formal requirement of the <script> element, these event handlers are focused on form elements. However, they can be used for a number of other elements on the page that a user might interact with. Some events are used exclusively with certain elements, while others can be used with a wide range of elements. You'll see both types in Table 1.
Event Handler |
The Event Is Triggered When... |
onfocus |
The user enters a form element (<input>, <select>, <textarea>, and <button>) or other input element (<a>, <label>) using the mouse or keyboard. |
onblur |
The user leaves a form element, hyperlink, or other input element (same elements as for onfocus), either by using the mouse or pressing a key. |
onclick |
The user clicks an element. |
ondblclick |
The user double-clicks an element. |
onchange |
The user changes a value and leaves a form element (used with <input>, <select>, and <textarea> only). |
onkeypress |
The user presses a key while an element has the focus. |
onkeydown |
The user holds a key down while an element has the focus. |
onkeyup |
The user releases a key while an element has the focus. |
onload |
The page loads (used with <body> or <frameset>). |
onunload |
The page is exited (<body or <frameset>). |
onmouseover |
The user points the mouse at an element. |
onmousedown |
The user holds the mouse button down while pointing at an element. |
onmouseup |
The user releases the mouse button while pointing at an element. |
onmousemove |
The user moves the mouse while it's over an element. |
onmouseout |
The user moves the mouse pointer away from an element that it had been pointing to. |
onselect |
The user selects either an <input> or <textarea> form input field. |
onreset |
The user resets a form (works only with the <form> element). |
onsubmit |
The user submits a form (works only with the <form> element) . |
Creating an event handler is simply a question of adding one of these handlers as an attribute to the element that will be the focus. Then, inside the handler's quotation marks, you either include scripting code or a function call. Here's an example that calls a built-in function:
<body onunload="alert('Thanks for visiting!')">
Incidentally, this example is the major reason that JavaScript will allow you to use either single or double quotes in your scripting, as long as you're consistent. If you used double quotes in this alert function (the function is being passed a string value), the onunload handler's quotes will be closed early, thus creating an invalid handler.
As noted, one way to respond to a user's input is through an alert box, which is similar to a dialog box except that it has only one button for a response. An alert box communicates directly with the user, often blocking the main document window until it's dismissed.
TIP
The newline character, \n, allows you to add a hard return in the middle of a text string used to create an alert box.
Aside from using built-in functions, such as alert(), you could call your own function from within the handler:
<input type="text" name="phoneNumber" onchange="checkPhone (this.value)" />
In this example, the checkPhone() function is called and passed the value of the <input> text entry box named phoneNumber. It does this by sending a pointer to that value, using the this keyword, which is discussed in the next section.
The this keyword is probably one of the odder ducks you'll encounter while trying to learn JavaScript. What it does, in essence, is stand in for the current object that has focus relative to the handler. Here's an example like the one discussed in the previous section:
<form name="myForm"> <input type="text" name="phoneNumber" onchange="checkPhone (this.value)" /> </form>
this is used to suggest "this input element," and value is a property that stores the value associated with this form element. You could also access that same value as the following in order to pass along the value:
<form name="myForm"> <input type="text" name="phoneNumber" onchange="checkPhone (document.myForm.phoneNumber.value)" /> </form>
Note that the name of the form and the name of the <input> element are both vital in getting at the correct value. That's one reason for the this keyword; another is simple convenience.
Next: Introducing the Document Object Model |