Seminar 3

Advanced JavaScript

© M. Firebaugh


I. Introduction


II. More JavaScript Syntax

How does JavaScript compare to Java?

JavaScript

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
</SCRIPT>

To link to a JavaScript file:


<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
...
</SCRIPT>
</HEAD>
<BODY>


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;

i=3;

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:

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

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

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.

<script><!--
// 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
Circle.prototype.pi=Math.PI;

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

//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);

// -->
</script>

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.

Event

Applies to

Occurs when

Event Handler

Abort
images User aborts the loading of an image (for example by clicking a link or clicking the Stop button)
onAbort
Blur
windows and all form elements User removes input focus from window or form element
onBlur
Change
text fields, textareas, select lists User changes value of element
onChange
Click
buttons, radio buttons, checkboxes, submit buttons, reset buttons, links User clicks form element or link
onClick
DragDrop
windows User drops an object onto the browser window, such as dropping a file on the browser window
onDragDrop
Error
images, windows The loading of a document or image causes an error
onError
Focus
windows and all form elements User gives input focus to window or form element
onFocus
KeyDown
documents, images, links, text areas User depresses a key
onKeyDown
KeyPress
documents, images, links, text areas User presses or holds down a key
onKeyPress
KeyUp
documents, images, links, text areas User releases a key
onKeyUp
Load
document body User loads the page in the Navigator
onLoad
MouseDown
documents, buttons, links User depresses a mouse button
onMouseDown
MouseMove
nothing by default User moves the cursor
onMouseMove
MouseOut
areas, links User moves cursor out of a client-side image map or link
onMouseOut
MouseOver
links User moves cursor over a link
onMouseOver
MouseUp
documents, buttons, links User releases a mouse button
onMouseUp
Move
windows User or script moves a window
onMove
Reset
forms User resets a form (clicks a Reset button)
onReset
Resize
windows User or script resizes a window
onResize
Select
text fields, textareas User selects form element's input field
onSelect
Submit
forms User submits a form
onSubmit
Unload
document body User exits the page
onUnload


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)
// -->
</script>
<hr width="&{barWidth};%" size="&{barSize};"
noshade="&{solid};" align="left">
// -->
</script>

Produces:





Example 2: Generalized Math Calculator

The JavaScript code below utilizes the valuable eval method:

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

produces:

calculator.html


Example 3: Array Example - WebSafe Colors

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

<SCRIPT LANGUAGE="JavaScript">
<!--
var hexPairs = new Array("33","66","99","AA","CC","FF");
var str = '';
// Strike up a table
document.writeln('<H2>Web Safe Colors</H2>
<TABLE BORDER=1 CELLSPACING=0>');
for (var i = 0; i < hexPairs.length; i++) {
// Create a row
document.writeln('<TR>');
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
document.writeln(str);
str = '';
}
// End the row
document.writeln('</TR>');
}
// End the table
document.writeln('</TABLE>');
//-->
</SCRIPT>

produces:


Example 4: Tracking Eyes

The two graphics used are:

eyes.gif: and eyeballs.gif:

Click on the link below and examine the JavaScript code.

Results:

No place to hide

Note:

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

  window.captureEvents(Event.MOUSEMOVE);
             window.onMouseMove=myhandler;

combined with the reading program in myHandler:

function myhandler(e)
{ex=e.pageX; 
 ey=e.pageY;
 moveeye()
 return routeEvent(e);
}

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

eyeballs location = (ae.left, ae.top)
left eye location = (le.left, le.top)
right eye location = (re.left, re.top)
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|http://www.uwp.edu/academic/computer.science/morris.csci/CS.105/Week.15/Lect30.www/Lect30.html",

"Autoscroll|JavaScript application that scrolls web pages for you|http://www.serve.com/hotsyte/wildman/autoscroll/auto_scroll.html",

"Left-Right Scroll|JavaScript application that scrolls web pages from left to right|http://www.serve.com/hotsyte/wildman/autoscroll/auto_scroll.html",

"Drop Box|JavaScript application that facilitates web site navigstion with &lt;SELECT&gt; lists|http://www.serve.com/hotsyte/wildman/dropbox/selfrm.html",

"E-mail Submission|JavaScript application that sends commands to LISTSERV mail servers|http://www.serve.com/hotsyte/wildman/email_submit/email_submit.html",

"Membership Application|JavaScript application that allows users to apply for online membership|http://www.serve.com/hotsyte/wildman/members_app/member_app.html",

"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|http://www.serve.com/hotsyte/",

"Instruction|JavaScript instruction, tutorials, links, examples, and downloadable or cut-and-paste scripts|http://www.serve.com/hotsyte/instruct.html",

"Interaction|JavaScript newsgroups, bulletin boards, mailing lists|http://www.serve.com/hotsyte/interact.html",

"Editorials|JavaScript articles with tips, dos and don'ts, and other advice about JavaScript|http://www.serve.com/hotsyte/editor.html",

"Wildman's Archive|Free JavaScript scripts and applications by the legendary Wildman Timothy Hobbs|http://www.serve.com/hotsyte/wildman/",

"The HotSyte Reserve|Cool scripts you can download, compliments of the HotSyte webmaster|http://www.serve.com/hotsyte/reserve.html",

"Publications|Books, e-zines, and other JavaScript-related publications|http://www.serve.com/hotsyte/books.html",

"Web Gear|The HotSyte download center for the latest browsers, plug-ins, and other cool web development software|http://www.serve.com/hotsyte/tools.html",

"Resources|JavaScript documentation, sites of interest, resources, reference, JavaScript research, and general information|http://www.serve.com/hotsyte/genref.html",

"Station HTML|Links to sites offering HTML intruction and reference|http://www.serve.com/hotsyte/html.html",

"Flash Animation|Macromedia Flash provides efficient vector graphics and animation|http://www.uwp.edu/academic/computer.science/morris.csci/CS.220/Week13.www/Lect25.www/Lect25.html",

"JavaScript, For Language Harmony|How to use JavaScript for multi-lingual sites|http://www.serve.com/hotsyte/079702.html",

"Steppin' In The Pooptoy|Pointers to keep your JavaScript beneficial to web site visitors|http://www.serve.com/hotsyte/069701.html",

"JavaScript DON'Ts: onMouseOver and You|An article about what not to do with the onMouseOver event|http://www.serve.com/hotsyte/039701.html",

"Interacting With Users: Alert(), Confirm(), and Prompt() Methods|How to use dialog boxes to increase web page interactivity|http://www.serve.com/hotsyte/019704.html",

"Employ \"Anti-explosion\" Tactics at Your JavaScript Site|How to avoid JavaScript errors|http://www.serve.com/hotsyte/019701.html",

"JavaScript: What's The Buzz?|An introduction to the concept and utility of JavaScript|http://www.serve.com/hotsyte/019702.html",

"Cyber Date Profile|JavaScript application that uses the cookie property to maintain the client state|http://www.serve.com/hotsyte/cybrdate.html",

"Bank Reserve|Simple JavaScript database application|http://www.serve.com/hotsyte/database.html",

"Ray Tracing|Realistic 3D design using ray tracing and POV Ray|http://www.uwp.edu/academic/computer.science/morris.csci/CS.120/Week.11/Lect21.www/Lect21.html",

"JavaScript E-mail|JavaScript application that allows users to send e-mail without a CGI program|http://www.serve.com/hotsyte/jsemail.html",

"The Arguments Array|Learn about the JavaScript argument object and its array|http://www.serve.com/hotsyte/argument.html",

"Synapse|JavaScript application and memory game where players must match pairs by memory and can choose skill levels|http://www.serve.com/hotsyte/download/synapse.zip",

"Fruit Shopper|JavaScript application that demonstrates the basics of HTML form validation|http://www.serve.com/hotsyte/fruit.html",

"Pythagorean Theorem Solver|JavaScript application that solves for the missing sides of right triangles|http://www.serve.com/hotsyte/triangle.html",

"Browser Identifier|JavaScript application that provides users with information about their browsers|http://www.serve.com/hotsyte/browser.html",

"Routing Browsers|JavaScript application that routs visitors to web pages according to browser|http://www.serve.com/hotsyte/routing.html",

"Google Search|The first fast, intelligent, multi-engine search program|http://www.google.com/",

"Shopping Cart|JavaScript application that facilitates online shopping|http://www.serve.com/hotsyte/wildman/shopping_cart/shop_cart._intro.html",

"JavaScript Guestbook|JavaScript application that uses cookies so users can read and write comments about the hosting web site|http://www.serve.com/hotsyte/wildman/guestbook/gb.html",

"Active Map|JavaScript application that demonstrates the utility of the image object with a map graphic|http://www.serve.com/hotsyte/wildman/active_map/active_map.html",

"Jukebox|JavaScript application that allows users to select from a list of audio clips|http://www.serve.com/hotsyte/wildman/jukebox/jukewindow.html",

"Scratchpad|JavaScript application that allows users to e-mail webmasters feedback|http://www.serve.com/hotsyte/wildman/scratchpad/open_scratchpad.html",

"Timed Images|JavaScript application that displays images at specified intervals|http://www.serve.com/hotsyte/wildman/url_timed_images/url_timed_images.html",

"UNICO Seminars|UNICO Seminar Series on Advanced Web Design and JavaScript|http://www.uwp.edu/academic/computer.science/morris.csci/AdvWebDesign.html"

);

The Results:

DataBase Search Engine



References:

Books

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

http://developer.netscape.com/docs/manuals/javascript.html

http://developer.netscape.com/docs/manuals/communicator/dynhtml/content.htm

http://www.w3.org/TR/DOM-Level-2/