One way to place JavaScript code in your document is via
the HTML and XHTML standard <script>
tag.
<script language="JavaScript">
<!--
JavaScript statements go here
// -->
</script>
For browsers that ignore the <script>
tag, the contents are masked
by the comment delimiters <!--
and -->
. JavaScript-enabled
browsers, on the other hand, automatically recognize and interpret the
JavaScript statements delimited by the comment tags. By using this
skeleton for all your <script>
tags, you can be sure that
all browsers handle your document gracefully, if not
completely.
Unfortunately, as we discuss in Chapter 16, script content for XHTML documents must be within a special CDATA declaration, rather than within comments. Hence, HTML browsers won't honor XHTML scripts, and vice versa. Our only recommendation at this point is to follow the popular browsers: write in HTML, but use as many of the features of XHTML as you can in preparation for the future.
You may include more than one <script>
tag in a document, located in
either the <head>
or the
<body>
. The
JavaScript-enabled browser executes the statements in order. Variables
and functions defined within one <script>
tag may be referenced by
JavaScript statements in other <script>
tags. In fact, one common
JavaScript programming style is to use a single <script>
in the document <head>
to define common functions and
global variables for the document and then to call those functions and
reference their variables in other JavaScript statements sprinkled
throughout the document.
Some JavaScript scripts create actual document content
using the document.write
method.
If your scripts do not alter the contents of the document, add the
defer
attribute to the <script>
tag to speed its
processing. Because the browser knows that it can safely read the
remainder of the document without executing your scripts, it defers
interpretation of the script until after the document has been
rendered for the user.
The <noscript>
tag
supports the six standard HTML 4/XHTML attributes—class
and style
for style management, lang
and dir
for language type and display direction,
title
and id
for titling and naming the enclosed
content—and the event attributes for user-initiated processing. [The dir attribute, 3.6.1.1]
[The lang attribute,
3.6.1.2] [The id
attribute, 4.1.1.4] [The
title attribute, 4.1.1.5] [Inline Styles: The style Attribute,
8.1.1] [Style Classes,
8.3] [JavaScript Event
Handlers, 12.3.3]
<a href="doc.html" onMouseOver="status='Click me!'; return true">
When the mouse passes over this example link, the browser executes the JavaScript statements. (Notice that the two JavaScript statements are enclosed in quotes and separated by a semicolon, and that single quotes surround the text-message portion of the first statement.)
While a complete explanation of this code is beyond our scope, the net result is that the browser places the message "Click me!" in the status bar of the browser window. Commonly, authors use this simple JavaScript function to display a more descriptive explanation of a hyperlink, in place of the often cryptic URL that the browser traditionally displays in the status window.
HTML and XHTML both support a rich set of event handlers
through related on
-event tag attributes. The value of any of
the JavaScript event-handler attributes is a quoted string containing
one or more JavaScript statements separated by semicolons. If
necessary, you can break extremely long statements across several
lines. You also should take care to use entities for embedded double
quotes in the statements, to avoid syntax errors when processing the
attribute values.
Table 12-1 presents the current set of event handlers as tag attributes. Most are supported by the popular browsers, which also support a variety of nonstandard event handlers (tagged with asterisks in the table).
We put the event handlers into two categories: user related
and document related. The user-related ones are the mouse and
keyboard events that occur when the user handles either device on
the computer. User-related events are quite ubiquitous, appearing as
standard attributes in nearly all the standard tags (even though
they may not yet be supported by any browser), so we don't list
their associated tags in Table
12-1. Instead, we'll tell you which tags do
not accept these event attributes: <applet>
, <base>
, <basefont>
, <bdo>
, <br>
, <font>
, <frame>
, <frameset>
, <head>
, <html>
, <iframe>
, <isindex>
, <meta>
, <param>
, <script>
, <style>
, and <title>
.
Table 12-1. Event handlers
Event handler | HTML/XHTML tags |
---|---|
[*] | |
| <img> |
| |
| |
onClick | Most tags |
onDblClick | Most tags |
| <img> |
| |
onKeyDown | Most tags |
onKeyPress | Most tags |
onKeyUp | Most tags |
| |
onMouseDown | Most tags |
onMouseMove | Most tags |
onMouseOut | Most tags |
onMouseOver | Most tags |
onMouseUp | Most tags |
| <form> |
| |
| <form> |
| |
[*] Nonstandard handlers. |
The onClick
,
onDblClick
, onMouseDown
, and onMouseUp
attributes refer to the mouse
button. The onClick
event happens
when the user presses down and then quickly releases the mouse
button. If the user then quickly clicks the mouse button for a
second time, the onDblClick
event
gets triggered in the browser as well.
The HTML 4 and XHTML standards currently support only
three events relating to user keyboard actions: onKeyDown
, onKeyUp
, and onKeyPress
. The onKeyDown
event occurs when the user
depresses a key on the keyboard; onKeyUp
happens when the key is released.
The onKeyPress
event is triggered
when a key is pressed and released. Usually, you'll have handlers
for either the up and down events or the composite key-press event,
but not for both.
Most of the document-related event handlers relate to the
actions and states of form controls. For instance, onReset
and onSubmit
happen when the user activates
the respective reset or submit button. Similarly, onSelect
and onChange
occur as users interact with
certain form elements. See Chapter
9 for a detailed discussion of these forms-related
events.
There also are some document-related event handlers that occur
when various document elements get handled by the browser. For
instance, the onLoad
event may
happen when a frameset is complete or when the body of an HTML or
XHTML document gets loaded and displayed by the browser. Similarly,
onUnload
occurs when a document
is removed from a frame or window.
To create a javascript URL, use javascript
as the URL's protocol:
<a href="javascript:generate_document()">
In this example, the JavaScript function generate_document()
gets executed whenever
the user selects the hyperlink. The value returned by the function,
presumably a valid HTML or XHTML document, is rendered and displayed
by the browser.
It may be that the executed statement returns no value. In this case, the current document is left unchanged. For example, this javascript URL:
<a href="javascript:alert('Error!')">
pops up an alert dialog box and does nothing else. The document containing the hyperlink is still visible after the dialog box is displayed and dismissed by the user.
Character entities in HTML and XHTML consist of an ampersand (&
), an entity name or number, and a
closing semicolon. For instance, to insert the ampersand character
itself in a document text flow, use the character sequence &
. Similarly, JavaScript entities
consist of an ampersand, one or more JavaScript
statements enclosed in curly braces, and a closing semicolon. For
example:
&{document.fgColor};
You must separate multiple statements by semicolons within the curly braces. The value of the last (or only) statement is converted to a string and replaces the entity in the document.
Normally, entities can appear anywhere in a document. JavaScript
entities, however, are restricted to values of tag attributes. This
lets you write "dynamic tags" whose attributes are not known until the
document is loaded and the JavaScript is executed. For example, this
tag sets the text color of the document to the color value returned by
the individual's favorite_color()
function:
<body text=&{favorite_color()};>
Support for JavaScript entities is inconsistent among the various browsers and for this reason we recommend against their use.