Copyright ©2002 by David Matuszek
JavaScript is not used to write standalone programs; it is used to write programs (and snippets of programs) that are included in an HTML Web page. Hence, to do anything meaningful with JavaScript, it is necessary to understand the internal structure of the Web page. This structure is given by the HTML DOM (Document Object Model).
There are three ways to add JavaScript to an HTML page:
<script type="text/javascript">...</script>
tags.
Since browsers ignore tags they don't understand, very old browsers that don't know JavaScript will ignore the start and end tags, but will display the enclosed JavaScript. To prevent this, use the following form (line arrangement is important):Function definitions should usually be placed in the
<script type="text/javascript">
<!--
your JavaScript
//-->
</script>
<head> of
the HTML document. Scripts in the <body> section are executed
as the page is loaded, and typically produce output that is displayed at that
point in the page. .js extension,
and load it with <script src="URL"></script> .js file may not itself contain <script> tags.)
This is the recommended way to write JavaScript that will be used on more
than one page.
<input type="button"
name="computeButton"
value="Compute!"
onclick="with (document.myForm) {
result.value=compute(myInput.value);
}">
The various event handlers will be described in the following sections. Here is a partial outline of the object hierarchy (most properties are read-only):
document -- the HTML document
anchors[ ] -- an array of anchors (<a
name=...> tags) in the document applets[ ] -- an array of Applet objects in the
documentembeds[ ] -- an array of embedded objects (like
plugins); used mostly by ASPforms[ ] -- an array of Form elements in the document
elements[ ] -- an array of form elements in
this form
images[ ] -- an array of images (<img
src-...> tags) in the document links[ ] -- an array of hyperlinks (<a
href-...> tags) in the document frames[ ] -- ahistory -- the browser's History objectlocation -- the URL of the currently displayed document;
changing it causes the new URL to be loadedscreen -- an object that represents the computer screennavigator -- an object that represents the browserThe window object
Window properties and methods do not require a prefix, as window.
is assumed.
windowselfwindow.parenttopframes[ ]lengthdocumentlocation
location.reload() will refresh the window.navigatorappName -- the name of the browser, such as "Netscape"platform -- the computer running the browser, such as "Win32"statusalert(string)string and
an OK button.confirm(string)string along
with Cancel and OK buttons. Returns true if OK
is pressed, false if Cancel is pressed.prompt(string)string, a
text field, and Cancel and OK buttons. Returns the string entered
by the user if OK is pressed, null if Cancel is
pressed.open(URL)URL.close()The document object
Because window is the default prefix, and document
is a property of window, you must prefix these properties and methods
with document., for example, .
anchors[ ]anchors.length Anchor objects, that is, objects
representing <a name=...>name.applets[ ]applets.length Applet objects. The properties of
an applet are the public fields defined in the applet, and its
methods are the public methods of the Applet. This is powerful
and useful, but remember that (1) Java is strongly typed, so you must supply
values of the correct types for the fields and method parameters, and (2)
any changes or method calls you make are done in a separate Thread.bgColorforms[ ]forms.length Form elements. If the document contains
only one form, it is forms[0]. Forms contain all the active user
GUI objects.images[ ]images.length Image objects. The most useful property
of an image is its src (URL). If you assign a new URL to this
property, that URL will be loaded.links[ ]links.length Link objects. A link has several properties,
including href, which holds the complete URL.titleURLwrite(string)string to the current document.The form object
A document may contain more than one form. The first
(and typically the only) such form is referred to by document.form[0].
elements[ ]elements.length form elements.HTML form elements may all have a name attribute, for example,
<input type="text" name="data" value="unknown">.
It is strongly recommended that form elements be given a name, as this name
may be referred to in JavaScript. For example, if form element 0 in form 0 has
the name "data", the following are equivalent:
document.forms[0].elements[0].value=5;
data.value=5;
Each form element can have attributes that act as event handlers. For example, a Button may be defined as follows:
<input type="button" onclick="data.value=99;" name="myButton" value="Click me!">
Here, onclick is an event handler that tells JavaScript what to
do (in this case, set data.value to 99) when the button
is clicked. Anything more complex than one or two statements should generally
be implemented as a function call.
Events
Numerous events can occur, and not every form element will respond to every
event. Browsers differ somewhat in which form elements will handle which events.
Here are the events and the form elements that should be able to handle
them. (Note: You will sometimes see these event names written with capital
letters, for example onMouseDown instead of onmousedown.
This works in HTML, which is case insensitive, but does not work in JavaScript,
which is case sensitive.)
onload -- the document or frameset has completed loading: <body>,
<frameset> onunload -- the document or frameset is unloaded: <body>,
<frameset> onfocus -- the form element gains focus (for example, by the
user tabbing to it): <button>, <input>,
<label>, <select>, <textarea>
onblur -- the form element loses the focus: <button>,
<input>, <label>, <select>,
<textarea> onclick -- the form element is clicked: most elementsondblclick -- the form element is clicked twice in close succession:
most elementsonmousedown -- the mouse button is pressed while over the form
element: most elementsonmouseover -- the mouse is moved over the form element: most
elementsonmouseout -- the mouse is moved away from the form element:
most elementsonmouseup -- the mouse button is released while over the form
element: most elementsonmousemove -- the mouse is moved: most elementsonkeypress -- a key is clicked while this form element has
focus: <input>, <textarea>onkeydown -- a key is depressed while this form element has
focus: <input>, <textarea>, <body>onkeyup -- a key is released while this form element has focus:
<input>, <textarea>, <body>onabort -- image loading has been interrupted: <img>onerror -- there was an error loading the image: <img>onselect -- the text is selected: <input>,
<textarea>onchange -- the form element loses focus with a different value
than it had when it gained focus: <input>, <textarea>,
<select>onreset -- the user has clicked a Reset button; return false
to prevent reset: <form>onsubmit -- the user has clicked a Submit button; return false
to prevent submission: <form>The following table gives approximately the same information, organized by type of form element.
| Object | Event Handlers | |||||||||
area |
|
|||||||||
input type="button" |
|
|||||||||
checkbox |
|
|||||||||
document |
|
|||||||||
fileupload |
|
|||||||||
form |
|
|||||||||
frame |
|
|||||||||
img |
|
|||||||||
layer |
|
|||||||||
link |
|
|||||||||
password |
|
|||||||||
radio |
|
|||||||||
reset |
|
|||||||||
select |
|
|||||||||
submit |
|
|||||||||
input type="text" |
|
|||||||||
textarea |
|
|||||||||
window |
|
Live examples
Not all browsers respond to the same set of events on each form element. Your browser identifies itself as:
The following is a "live" test of capturing events from form elements. Every form element contains the code
onEvent="tell(this.name,
'onEvent');" for each of the following events: onmousedown,
onmouseup, onclick, ondblclick, onfocus,
onblur, onmouseover, onmouseout, onchange,
onkeypress, onkeydown, onkeyup, onselect,
and onreset. Use the mouse, keyboard, Tab and Return keys to explore
the behavior of these elements. You should expect to get different results in
different browsers.
document.write("This is <i>easy.</i>");
<script type="text/javascript">
var d = new Date()
document.write(d.getDate() + "/")
document.write((d.getMonth() + 1) + "/")
document.write(d.getFullYear())
</script>
<script type="text/javascript">
var d=new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul",
"Aug","Sep","Oct","Nov","Dec")
document.write(weekday[d.getDay()] + ", ")
document.write(monthname[d.getMonth()] + " " + d.getDate() + ", ")
document.write(d.getFullYear())
</script>
<script type="text/javascript">
document.write(Math.random())
</script>
<script type="text/javascript">
var max = 10;
number=Math.random()*max + 1;
document.write(Math.floor(number));
</script>
<form>  // Buttons can only occur within forms
<input type="button" name="Submit" value="Alert!"
onclick="alert('Oh oh, something happened!');">
</form>