Seminar 3

Advanced JavaScript

© M. Firebaugh

I. Introduction

II. More JavaScript Syntax

How does JavaScript compare to Java?



Interpreted (not compiled) by client. Compiled bytecodes downloaded from server, executed on client.
Object-based. No distinction between types of objects. Inheritance is through the prototype mechanism and properties and methods can be added to any object dynamically. Object-oriented. Objects are divided into classes and instances with all inheritance through the class hieararchy. Classes and instances cannot have properties or methods added dynamically.
Code integrated with, and embedded in, HTML. Applets distinct from HTML (accessed from HTML pages).
Variable data types not declared (loose typing). Variable data types must be declared (strong typing).
Dynamic binding. Object references checked at runtime. Static binding. Object references must exist at compile-time.
Cannot automatically write to hard disk. Cannot automatically write to hard disk.

Four Modes of Embedding JavaScript in HTML Documents

  1. As statements and functions within a <SCRIPT> Tag
  2. By specifying a file as the JavaScript Source
  3. By specifying a JavaScript expression as the value of an HTML attribute [e.g., <HR WIDTH="&{barWidth};%" ALIGN="LEFT">
  4. As event handlers within certain HTML tags (mostly form elements)

Recall, JavaScripts may be multiple and appear in either the <HEAD> or <BODY>, and are generally of the form:

<SCRIPT  LANGUAGE = "JavaScript">
script goes here

To link to a JavaScript file:

<SCRIPT SRC="common.js">

III. JavaScript Arrays

Recall in Introduction to JavaScript we described simple data types: strings, numbers, and Boolean variables which were used to store a single variable. Most "industrial strength" programs process large numbers of variables for which arraysare essential.

Syntax for creating a JavaScript array using the Array constructor includes:

var a = new Array();

This creates an empty array with no elements.

The second method for using the Array constructor explicitly specifies values for the first n elements of the array:

var b = new Array(5,4,3,2,1,"testing", "testing")

Here each argument in the list specifies and element value and may be of any type.

The third method for using the constructor to create an array is:

var c = new Array(10)

This creates an array of length 10 with undefined values, but with the length property of value 10.

Arrays may also be created using assignment of array literals:

var primes = [2,3,5,7,11];

var d = ["a", true, 3.14];

Note again that JavaScript's "weak typing" allows the mixing of data types.

Finally, array literals may contain other array literals or object literals (see next section).

var e = [[1, {x:1, y:2}],[2, {x:3, y:4}]]

This allows very powerful and complex data structures.

Reading and Writing Elements of Arrays

The following are all correct syntax for assigning and accessing elements of arrays:

value = a[0];

a[2] = 6.28;


b[i] = 5;

c[i+1]="hello world";

d[d[i]] = d[0];

JavaScript (like C, C++, and Java) starts counting array elements at 0. So, for instance, although primes.length = 5, we have:

primes[0] = 2

primes[4] = 11

Arrays in JavaScript are sparce(unlike arrays in C and Java). Thus, the code:

a[0] = 1;

a[1000] = "Element one thousand";

will require only two storage locations in memory, even though

a.length = 1001

Array Methods

JavaScript supports about a dozen methods for operating on arrays. Among the more useful are:

Array.join() converts all the elements of an array to a string and concatenates them.

var a = [10, 20, 30];    // Create an array

s = a.join(); // Returns string "10,20,30"

t = a.join(""); // Returns string "102030"

r = a.join(" "); // Returns string "10 20 30"

Note: the default separator for the Array.join() method is the comma, ",".

Array.reverse() reverses the order of the elements of an array. Operating on the above a array, the following code produces:

s = a.reverse(" ");  // returns 30 20 10

t = a.reverse(); // returns 30,20,10

Note: again, the default separator for the Array.reverse() method is the comma, but the values returned are the same data type as the elements of array a.

Array.sort() sorts elements of an array into alphabetical order when called with no arguments. If elements are numerical it converts them to strings and then sorts them.

b=new Array("banana", "cherry", "apple");

b.sort(); // returns "apple","banana","cherry"

var c=[33, 4, 1111, 222];

c.sort(); // returns 1111,222,33,4

See, both array b and array c are sorted "in place" alphabetically, but the type of c remains numerical.

How could we sort the original c array into increasing numerical order? We need a comparison function as the argument to sort(). The following code will do it:

var c=[33, 4, 1111, 222]; 

c.sort(function(c,d) {

return c - d;

}); // returns 4,33,222,1111

The function(c,d) returns a negative number if c < d (i.e., in correct order), a zero if c = d (also correct order), and a positive number if c > d. The sort function does a type of bubble sort, with the initial arguments (c,d) = (c[3],c[0]) respectively. To understand the operation of the sort function, it is useful to insert alert( c + " " + d); just ahead of the return c - d statement.

Array.concat() return the original array augmented by the arguments of concat. For instance, the following code produces:

var a = [1,2,3];

a.concat(4,5); // returns [1,2,3,4,5]

a.concat([4,5]); // returns [1,2,3,4,5]

a.concat([4,5],[6,7]); // returns [1,2,3,4,5,6,7]

a.concat(4,[5,[6,7]]); // returns [1,2,3,4,5,[6,7]]

Note how Array.concat() flattens arrays but does not recursively flattens arrays of arrays.

In addition to these obviously valuable methods, JavaScript provides the array methods: slice(), splice(), push(), pop(),unshift(), shift(), toString(), and toSource().

IV. Objects and their Properties

In addition to simple string, number, and Boolean data types and numbered arrays of these types, JavaScript supports Objects. Objects are compound types aggregating multiple data values into single units. Consider the following JavaScript code:

function listPropertyNames(obj){
var names="";
for(var i in obj) names += i + "\n";
// -->
var circle = {x:0, y:0, radius:2};
var homer = {
name: "Homer Simpson",
age: 34,
married: true,
occupation: "plant operator",
email: ""
var square = new Function("x", "return x*x;");
document.write("<BR>" + homer.occupation);

which produces:

Object Property Report

What can we learn from this example?

1. The function listPropertyNames uses the for/in repetition control structure whose syntax is:

for (variable in object)

2. The statement names += i + "\n" is equivalent to names = names + i [CRLF].

3. New object literals circle and homer are created as a comma-separated list of property specifications enclosed within curly braces.

4. The new function object square(x) is created by the new operator working with the Function() constructor.

5. Notice how the listPropertyNames function correctly lists the properties of the circle, homer, and square objects.

6. Notice how correct values calculated by the square function are reported by the alert and document.write output methods.

7. Notice how the occupation property of homer is correctly referenced by homer.occupation and reported with a document.write.

8. Notice how the properties of background objects window and document are reported.

9. Finally, notice how typeof reports that homer is of type object.

V. Building JavaScript Classes using Prototypes

One feature of OOP is the concept of class and the efficiencies possible through inheritance of the properties of the class prototype by instances of the class. Classes in JavaScript are defined through the use of the prototype object. Consider how we can define the Circle class with properties of area and circumference.

// Define the Circle class
function Circle(x,y,r){
this.x=x; // x-coordinate of center of circle
this.y=y; // y-coordinate of center of circle
this.r=r; // Radius of circle

// Create an initial Circle object
new Circle(0,0,0);

//Define the constant pi using the Math object

//Define the method for computing the circumference
function circleCircumference(){return 2*this.pi*this.r;}

//Define the area method using the Function constructor
Circle.prototype.area=new Function("return this.pi*this.r*this.r;");

//The Circle class is now defined.
//Next we create a particular instance and invoke methods to compute its properties
var c1=new Circle(0.0,0.0,1.0);
var a1=c1.area();
var p1=c1.circumference();
document.write("Area ="+a1+"<BR>"+"Circumference ="+p1);

// -->

produces the result:

Circle Class with Instance and Methods

VI. JavaScript Built-In Event Methods

JavaScript supports a large array of Events which are detected by Event Handler methods. The problem is that each event is sensitive to only certain HTML elements. Thus, for instance, the Click event, detected by the onClick event handler can only be used with form elements and links.


Applies to

Occurs when

Event Handler

images User aborts the loading of an image (for example by clicking a link or clicking the Stop button)
windows and all form elements User removes input focus from window or form element
text fields, textareas, select lists User changes value of element
buttons, radio buttons, checkboxes, submit buttons, reset buttons, links User clicks form element or link
windows User drops an object onto the browser window, such as dropping a file on the browser window
images, windows The loading of a document or image causes an error
windows and all form elements User gives input focus to window or form element
documents, images, links, text areas User depresses a key
documents, images, links, text areas User presses or holds down a key
documents, images, links, text areas User releases a key
document body User loads the page in the Navigator
documents, buttons, links User depresses a mouse button
nothing by default User moves the cursor
areas, links User moves cursor out of a client-side image map or link
links User moves cursor over a link
documents, buttons, links User releases a mouse button
windows User or script moves a window
forms User resets a form (clicks a Reset button)
windows User or script resizes a window
text fields, textareas User selects form element's input field
forms User submits a form
document body User exits the page

General Syntax for Handling Events:

<TAG  eventHandler="JavaScript Code"> 

These are particularly useful for FORMS (see Example 3 below):

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">

VII. Scripting with GoLive Button Images

Task: Redesign Instructor's Home Page with Rollover Buttons

1. Create five independent, transparent GIFs, . . . for Off state

2. Create five alternative, transparent GIFs, . . . for On state

3. Create an image which will serve as a background for the buttons,

4. Drag a Layout Grid from the Basic Palette onto your page in Layout mode

5. Drag the Image icon from the Basic Palette onto the upper-lefthand corner of the Layout Grid, and select your background image.

6. Drag a Floating Box onto the background image, position it, and reshape it to hold the rollover buttons

7. Switch to the Cyber Objects palette, and drag a Button Image into the correct location in the Floating Box

8. The Button Inspector will now open, with "Main" Image selected. Browse for the appropriate OFF button file.

9. Next, with the button selected, click on the "Over" button, and Browse for the appropriate ON button file

10. Switch to Status & Link tab to link buttons to URLs you wish to jump to

11. Whatever you do, DON'T look at the ugly code which GoLive generates to implement this!

VIII. JavaScript Examples

Example 1: JavaScript code segments to set HTML tag attributes

The following code:

<script language="JavaScript1.2">
var barWidth=50
var barSize=15
var solid=true
document.write(barWidth," ",barSize)
// -->
<hr width="&{barWidth};%" size="&{barSize};"
noshade="&{solid};" align="left">
// -->


Example 2: Generalized Math Calculator

The JavaScript code below utilizes the valuable eval method:

<!--- Hide script from old browsers
function compute(f) {
if (confirm("Are you sure?"))
f.result.value = eval(f.expr.value)
alert("Please come back again.")
// end hiding from old browsers -->
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate"
<INPUT TYPE="text" NAME="result" SIZE=15 >



Example 3: Array Example - WebSafe Colors

The JavaScript code using array hexPairs and a triple nested for loop:

var hexPairs = new Array("33","66","99","AA","CC","FF");
var str = '';
// Strike up a table
document.writeln('<H2>Web Safe Colors</H2>
for (var i = 0; i < hexPairs.length; i++) {
// Create a row
for (var j = 0; j < hexPairs.length; j++) { for (var k = 0; k < hexPairs.length; k++) {
// Create a string of data cells for the row with
whitespace in each
// Notice each background color is made with three
hexPairs elements
str += '<TD BGCOLOR="' + hexPairs[i] + hexPairs[j] +
hexPairs[k] + '">' + '&nbsp;&nbsp;&nbsp</TD>';
// Write the row of data cells and "reset" str
str = '';
// End the row
// End the table


Example 4: Tracking Eyes

The two graphics used are:

eyes.gif: and eyeballs.gif:

Click on the link below and examine the JavaScript code.


No place to hide


1. Reading the current cursor position is done with the code in function setHandlers():


combined with the reading program in myHandler:

function myhandler(e)
 return routeEvent(e);

2. The distance between the cursor and eyeballs is then calculated, using the variables:

eyeballs location = (ae.left,
left eye location = (le.left,
right eye location = (re.left,
current eyeballs location = (X0,Y0)
cursor location = (ex, ey)

3. The eye's "focus" is calculated by measuring the differences in position between the cursor and the center of the eyeballs

dy = ey - y0 -20  // y difference
dx1 = ex - x0 - 20  // left eye difference
dx2 = ex - x0 - 60  //  right eye difference

Example 5: Client-Side Search Engine

A typical database application involves sophisticated search of a client-side database. Assume your database is a JavaScript array of WWW addresses of essential sites (like a bookmark list) in the format:

"Link name  |  site description  |  URL"

We would like our search engine to perform several functions:

The Interface:

The Database:

profiles = new Array(
"A-Life & Emergent Computation|Emergent computation, A-Life, neural networks offer new paradigms|",

"Autoscroll|JavaScript application that scrolls web pages for you|",

"Left-Right Scroll|JavaScript application that scrolls web pages from left to right|",

"Drop Box|JavaScript application that facilitates web site navigstion with &lt;SELECT&gt; lists|",

"E-mail Submission|JavaScript application that sends commands to LISTSERV mail servers|",

"Membership Application|JavaScript application that allows users to apply for online membership|",

"HotSyte- The JavaScript Resource|Home page for tutorials, examples, scripts, links, instruction, Netscape articles, editorials, links, newsgroups, JavaScript books, a JavaScript web ring, and web development software|",

"Instruction|JavaScript instruction, tutorials, links, examples, and downloadable or cut-and-paste scripts|",

"Interaction|JavaScript newsgroups, bulletin boards, mailing lists|",

"Editorials|JavaScript articles with tips, dos and don'ts, and other advice about JavaScript|",

"Wildman's Archive|Free JavaScript scripts and applications by the legendary Wildman Timothy Hobbs|",

"The HotSyte Reserve|Cool scripts you can download, compliments of the HotSyte webmaster|",

"Publications|Books, e-zines, and other JavaScript-related publications|",

"Web Gear|The HotSyte download center for the latest browsers, plug-ins, and other cool web development software|",

"Resources|JavaScript documentation, sites of interest, resources, reference, JavaScript research, and general information|",

"Station HTML|Links to sites offering HTML intruction and reference|",

"Flash Animation|Macromedia Flash provides efficient vector graphics and animation|",

"JavaScript, For Language Harmony|How to use JavaScript for multi-lingual sites|",

"Steppin' In The Pooptoy|Pointers to keep your JavaScript beneficial to web site visitors|",

"JavaScript DON'Ts: onMouseOver and You|An article about what not to do with the onMouseOver event|",

"Interacting With Users: Alert(), Confirm(), and Prompt() Methods|How to use dialog boxes to increase web page interactivity|",

"Employ \"Anti-explosion\" Tactics at Your JavaScript Site|How to avoid JavaScript errors|",

"JavaScript: What's The Buzz?|An introduction to the concept and utility of JavaScript|",

"Cyber Date Profile|JavaScript application that uses the cookie property to maintain the client state|",

"Bank Reserve|Simple JavaScript database application|",

"Ray Tracing|Realistic 3D design using ray tracing and POV Ray|",

"JavaScript E-mail|JavaScript application that allows users to send e-mail without a CGI program|",

"The Arguments Array|Learn about the JavaScript argument object and its array|",

"Synapse|JavaScript application and memory game where players must match pairs by memory and can choose skill levels|",

"Fruit Shopper|JavaScript application that demonstrates the basics of HTML form validation|",

"Pythagorean Theorem Solver|JavaScript application that solves for the missing sides of right triangles|",

"Browser Identifier|JavaScript application that provides users with information about their browsers|",

"Routing Browsers|JavaScript application that routs visitors to web pages according to browser|",

"Google Search|The first fast, intelligent, multi-engine search program|",

"Shopping Cart|JavaScript application that facilitates online shopping|",

"JavaScript Guestbook|JavaScript application that uses cookies so users can read and write comments about the hosting web site|",

"Active Map|JavaScript application that demonstrates the utility of the image object with a map graphic|",

"Jukebox|JavaScript application that allows users to select from a list of audio clips|",

"Scratchpad|JavaScript application that allows users to e-mail webmasters feedback|",

"Timed Images|JavaScript application that displays images at specified intervals|",

"UNICO Seminars|UNICO Seminar Series on Advanced Web Design and JavaScript|"


The Results:

DataBase Search Engine



Dynamic HTML The Definitive Reference by Danny Goodman, O'Reilly & Associates, Sebastopol, CA (1998)

JavaScript for the World Wide Web (Third Ed.) by Tom Negrino and Dori Smith, Peachpit Press, Berkeley, CA (1998)

JavaScript Bible (Third Ed.) by Danny Goodman, IDG Books, Foster City, CA (1998)

JavaScript The Definitive Guide (Third Ed.) by David Flanagan, O'Reilly & Associates, Sebastopol, CA (1998)

JavaScript Goodies by Joe Burns & Andree Growney, Que Earthweb Press, Indianapolis, IN (1999)

JavaScript Application Cookbook by Jerry Bradenbaugh, O'Reilly & Associates, Sebastopol, CA (1999)

Web Sites URLs

Cross Browser Events for Dynamic HTML by James Robertson

The Minimalist Approach to Dynamic HTML by James Robertson