A Concise Introduction to JavaScript
Part II: Client-side JavaScript

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:

The HTML DOM (Document Object Model)

Here is a partial outline of the object hierarchy (most properties are read-only):

The window object

Window properties and methods do not require a prefix, as window. is assumed.

The current window (not usually needed).
Same as window.
If in a frame, the immediately enclosing window.
If in a frame, the outermost enclosing window.
frames[ ]
An array of frames (if any) within the current window. Frames are themselves windows.
The number of frames contained in this window.
The HTML document being displayed in this window.
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 location.reload() will refresh the window.
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"
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 just status--don't know why.)
Displays an alert dialog box containing the string and an OK button.
Displays a confirmation box containing the string along with Cancel and OK buttons. Returns true if OK is pressed, false if Cancel is pressed.
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.
Opens a new window containing the document specified by the URL.
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) after delay milliseconds. Returns a timeout id.
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) every interval milliseconds. Returns an interval id.
Cancels the periodic execution of code started by setInterval.

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, document.write("Hello").

anchors[ ]
An array of anchors.length Anchor objects, that is, objects representing <a name=...> tags. The only platform-independent property of an anchor is its name.
applets[ ]
An array of 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.
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 is forms[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 its src (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, including href, which holds the complete URL.
A read-only string containing the title of the document.
A read-only string containing the URL of the document.
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 the string.

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[ ]
An array of 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 a form:
Outside the form (usually, in a function defined in the head element):


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 Nodes. Subclasses of Node are Element, Attr (attribute), Text, Comment, Document, and DocumentFragment.


Text and Comment nodes have a nodeValue property that contains their text. You can change the text by assigning to this property.

All Nodes have parentNode, firstChild, nextSibling, previousSibling, and lastChild properties. These properties are read only.

Elements have a read-only tagName 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.


Returns the Element with the given id.
Returns an array of Elements with the given tagName.
Returns a new Element with the given tagName.
element.setAttribute(name, value)
Sets the element's name attribute to the given value.
Returns true if node is an Element and has attributes.
Returns true if node has children.
Adds a new child Node newChild to node.
Removes the given oldChild from node.

Attaching actions to form elements

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.)

The following table gives approximately the same information, organized by type of form element.

Object Event Handlers
ondblclick() onmouseout() onmouseover()
input type="button"
onblur() onfocus() onmouseup()
onclick() onmousedown()  
onblur() onclick() onfocus()
onclick() onkeypress() onmouseup()
ondblclick() onkeyup()  
onkeydown() onmousedown()  
onblur() onchange() onfocus()
onreset() onsubmit()  
onblur() onfocus() onresize()
ondragdrop() onload() onunload()
onerror() onmove()  
onabort() onkeydown() onkeyup()
onerror() onkeypress() onload()
onmouseover() onload() onblur()
onmouseout() onfocus()  
onclick() onkeypress() onmouseout()
ondblclick() onkeyup() onmouseup()
onkeydown() onmouseDown() onmouseover()
onblur() onfocus()  
onblur() onclick() onfocus()
onblur() onclick() onfocus()
onblur() onchange() onfocus()
onblur() onclick() onfocus()
input type="text"
onblur() onfocus()  
onchange() onselect()  
onblur() onkeydown() onselect()
onchange() onkeypress()  
onfocus() onkeyup()  
onblur() onfocus() onresize()
ondragdrop() onload() onunload()
onerror() onmove()  

Live examples

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.
<input type="button">

<input type="text">

<input type="password">

<select multiple>
<input type="hidden">
<input type="submit">
< input type="checkbox">
Study CIT597


<input type="reset">
<input type="radio">
Radio button 1
Radio button 2
 <option value="URL">

<a href>

What just happened:


Simple JavaScript snippets

Write text (and HTML) to page:
<script type="text/javascript">document.write("This is <i>easy.</i><br>");</script>
Read and write text fields :
  <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...">
Enter some text here:
Then click this button:
Text should appear here:
Get the date:
<script type="text/javascript">
    var d = new Date()
    document.write(d.getDate() + "/")
    document.write((d.getMonth() + 1) + "/")
Get and format the date:
<script type="text/javascript">
    var d=new Date()
    var weekday=new Array("Sunday","Monday","Tuesday","Wednesday",
    var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul",
    document.write(weekday[d.getDay()] + ", ")
    document.write(monthname[d.getMonth()] + " " + d.getDate() + ", ")
Get a random floating point number between 0 and 1:
<script type="text/javascript">
Get a random integer between 1 and N:
<script type="text/javascript">
var max = 10;
number=Math.random()*max + 1;
Display an alert box (when button is clicked):
<form>  // Buttons can only occur within forms
    <input type="button" name="Submit" value="Alert!"
              onclick="alert('Oh oh, something happened!');">
// Buttons can only occur within forms