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.

Properties
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 location.reload() will refresh the window.
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 just status--don't know why.)
Methods
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. Returns true 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) after delay 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) every interval milliseconds. Returns an interval id.
clearTimeout(intervalId)
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").

Properties
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.
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 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.
title
A read-only string containing the title of the document.
URL
A read-only string containing the URL of the document.
Methods
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 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:
     elements[0].value=5;
     data.value=5;
Outside the form (usually, in a function defined in the head element):
     document.forms[0].elements[0].value=5;
     document.forms[0].data.value=5;

The W3C DOM

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.

Properties

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.

Methods

document.getElementById(id)
Returns the Element with the given id.
document.getElementsByTagName(tagName)
Returns an array of Elements with the given tagName.
document.createElement(tagName)
Returns a new Element with the given tagName.
element.setAttribute(name, value)
Sets the element's name attribute to the given value.
node.hasAttributes()
Returns true if node is an Element and has attributes.
node.hasChildNodes()
Returns true if node has children.
node.appendChild(newChild)
Adds a new child Node newChild to node.
node.removeChild(oldChild)
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.

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

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

Object Event Handlers
area
ondblclick() onmouseout() onmouseover()
input type="button"
onblur() onfocus() onmouseup()
onclick() onmousedown()  
checkbox
onblur() onclick() onfocus()
document
onclick() onkeypress() onmouseup()
ondblclick() onkeyup()  
onkeydown() onmousedown()  
fileupload
onblur() onchange() onfocus()
form
onreset() onsubmit()  
frame
onblur() onfocus() onresize()
ondragdrop() onload() onunload()
onerror() onmove()  
img
onabort() onkeydown() onkeyup()
onerror() onkeypress() onload()
layer
onmouseover() onload() onblur()
onmouseout() onfocus()  
link
onclick() onkeypress() onmouseout()
ondblclick() onkeyup() onmouseup()
onkeydown() onmouseDown() onmouseover()
password
onblur() onfocus()  
radio
onblur() onclick() onfocus()
reset
onblur() onclick() onfocus()
select
onblur() onchange() onfocus()
submit
onblur() onclick() onfocus()
input type="text"
onblur() onfocus()  
onchange() onselect()  
textarea
onblur() onkeydown() onselect()
onchange() onkeypress()  
onfocus() onkeyup()  
window
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

<select>

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

<a href>
http://www.google.com

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...">
  </form>
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) + "/")
    document.write(d.getFullYear())
</script>
Get and format the date:
<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>
Get a random floating point number between 0 and 1:
<script type="text/javascript">
    document.write(Math.random())
</script>
Get a random integer between 1 and N:
<script type="text/javascript">
var max = 10;
number=Math.random()*max + 1;
document.write(Math.floor(number));
</script>
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!');">
</form>
// Buttons can only occur within forms