Copyright ©2002, ©2007 by David Matuszek
JavaScript is seldom 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 four 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):
<script type="text/javascript">
<!--
your JavaScript
//-->
</script>
<noscript>text</noscript>
tag
will be displayed if and only if JavaScript is unavailable or disabled. <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.The various event handlers will be described in the following sections.<input type="button" name="computeButton" value="Compute!" onclick="with (document.myForm) { result.value=compute(myInput.value); }">
javascript:
protocol.
If the JavaScript returns a value other than undefined
, it will
overwrite the current document; to avoid this, use the void
method.
For example:
<form action="javascript:void add(2,2)">
Here is a partial outline of the object hierarchy (most properties are read-only):
window
-- the current window; acts as the default
prefix for names
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 browserwindow
objectWindow properties and methods do not require a prefix, as window.
is assumed.
window
- The current window (not usually needed).
self
- Same as
window
.parent
- If in a frame, the immediately enclosing window.
top
- If in a frame, the outermost enclosing window.
frames[ ]
- An array of frames (if any) within the current window. Frames are themselves windows.
length
- The number of frames contained in this window.
document
- The HTML document being displayed in this window.
location
- The URL of the document being displayed in this window. If you set this property to a new URL, that URL will be loaded into this window. Calling
will refresh the window.
location.reload() navigator
- A reference to the Navigator (browser) object. Some properties of Navigator are:
appName
-- the name of the browser, such as "Netscape"
platform
-- the computer running the browser, such as "Win32"status
- A read/write string displayed in the status area of the browser window. Can be changed with a simple assignment statement. (Note: I've had to assign to
window.status
, not juststatus
--don't know why.)
alert(string)
- Displays an alert dialog box containing the
string
and an OK button.confirm(string)
- Displays a confirmation box containing the
string
along with Cancel and OK buttons. Returnstrue
if OK is pressed,false
if Cancel is pressed.prompt(string)
- Displays a confirmation box containing the
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)
- Opens a new window containing the document specified by the
URL
.close()
- Closes the given window (which should be a top-level window, not a frame).
setTimeout(code, delay)
- Sets a timer to execute the
code
(which may be a function or a string) afterdelay
milliseconds. Returns a timeout id.clearTimeout(timeoutId)
- Cancels a pending timeout started by
setTimeout
.setInterval(code, interval)
- Sets a timer to execute the
code
(which may be a function or a string) everyinterval
milliseconds. Returns an interval id.clearTimeout(intervalId)
- Cancels the periodic execution of code started by
setInterval
.
document
objectBecause window
is the default prefix, and document
is a property of window
, you must prefix these properties and methods
with document.
, for example,
.
anchors[ ]
- An array of
anchors.length
Anchor objects, that is, objects representingtags. The only platform-independent property of an anchor is its <a name=...>
name
.applets[ ]
- An array of
applets.length
Applet objects. The properties of an applet are thepublic
fields defined in the applet, and its methods are thepublic
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.bgColor
- The background color of the document. May be changed at any time.
forms[ ]
- An array of
forms.length
Form elements. If the document contains only one form, it isforms[0]
. Forms contain all the active user GUI objects.images[ ]
- An array of
images.length
Image objects. The most useful property of an image is itssrc
(URL). If you assign a new URL to this property, that URL will be loaded.links[ ]
- An array of
links.length
Link objects. A link has several properties, includinghref
, which holds the complete URL.title
- A read-only string containing the title of the document.
URL
- A read-only string containing the URL of the document.
write(string)
- Writes the specified
string
to the current document at the current location. This is only useful as a direct action while the document is loading; later, for example in an event handler, it will replace the current document with thestring
.
form
objectA 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:
Inside aform
:
elements[0].value=5;
data.value=5;
Outside theform
(usually, in a function defined in thehead
element):
document.forms[0].elements[0].value=5;
document.forms[0].data.value=5;
The W3C DOM adds features that make it possible to read and modify any HTML element. Only a very few of these features are discussed here.
The HTML document is regarded as a tree of Node
s. Subclasses
of Node
are Element
,
Attr
(attribute), Text
, Comment
, Document
,
and DocumentFragment
.
Text
andComment
nodes have anodeValue
property that contains their text. You can change the text by assigning to this property.All
Node
s haveparentNode
,firstChild
,nextSibling
,previousSibling
, andlastChild
properties. These properties are read only.
Element
s have a read-onlytagName
property, which is the HTML tag name in uppercase.In general, the contents of tags and the values of their attributes can usually be changed just by assigning new values to them.
document.getElementById(id)
- Returns the
Element
with the givenid
.
document.getElementsByTagName(tagName)
- Returns an array of
Element
s with the giventagName
.
document.createElement(tagName)
- Returns a new
Element
with the giventagName
.
element.setAttribute(name, value)
- Sets the element's
name
attribute to the givenvalue
.
node.hasAttributes()
- Returns true if
node
is anElement
and has attributes.
node.hasChildNodes()
- Returns true if
node
has children.
node.appendChild(newChild)
- Adds a new child
Node
newChild
tonode
.
node.removeChild(oldChild)
- Removes the given
oldChild
fromnode
.
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.
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 |
|
This section is for viewing in a browser, as it contains "live" examples of JavaScript. If you are reading a printed copy, this section may not make much sense.
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.
<script type="text/javascript">document.write("This is <i>easy.</i><br>");</script>
<form action=""> Enter some text here: <input type="text" name="from" value=""><br /> Then click this button: <input type="button" name="do_it" value="Copy text" onclick="to.value=from.value"><br /> Text should appear here: <input type="text" name="to" value="Waiting..."> </form>
<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>