2.1 JavaScript in HTML
JavaScript code may be embedded in HTML files in the form of scripts,
event handlers and URLs, as detailed below.
2.1.1 The <script> tag
Most JavaScript code appears in HTML files between a
<script> tag and a
</script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
In JavaScript 1.1 and later you can use the src
attribute of the <script> tag to specify the
URL of an external script to be loaded and executed. Files of
JavaScript code typically have a .js extension.
Note that the </script> tag is still
required when this attribute is used:
<script src="library.js"></script>
HTML allows scripts to be written in languages other than JavaScript,
and some browsers, such as Internet Explorer, support languages such
as VBScript. You can use the language attribute to
specify what language a script is written in. This attribute defaults
to "JavaScript"
in all browsers, so you do not usually have to set it. You can also
use attribute values such as
"JavaScript1.3" and
"JavaScript1.5" to specify the
version of JavaScript your code uses. Browsers that do not support
the specified version of the language simply ignore the script.
HTML 4 does not actually recognize the language
attribute of the <script> tag. Instead, the
official way to specify the language a script is written in is with
the type attribute. For JavaScript, set this
attribute to the MIME type
"text/javascript":
<script src="functions.js"
language="JavaScript1.5"
type="text/javascript"></script>
2.1.2 Event handlers
JavaScript code may also appear as the value of an event handler
attribute of an HTML tag. Event handler attribute names always begin
with "on". The code specified by
one of these attributes is executed when the named event occurs. For
example, the following HTML creates a button, and the
onclick attribute specifies an event handler that
displays an alert (a dialog box) when the user clicks the button:
<input type="button" value="Press Me"
onclick="alert('Hello World!');">
A list of other available event handler attributes is included later
in this section.
2.1.3 JavaScript URLs
JavaScript code may appear in a URL that uses the special
javascript: pseudo-protocol. The content of such a
URL is determined by evaluating the JavaScript code and converting
the resulting value to a string. If you want to use a JavaScript URL
to execute JavaScript code without returning any document content
that would overwrite the current document, use the
void operator:
<form action="javascript:void validate( )">
|