HELP! * GREY=local Full HTML for

LOCAL foilset JavaScript Tutorial for CPS616 Technologies of the Information Age 1997

Given by Geoffrey C. Fox at Basic Information Track of CPS on Spring Semester 97. Foils prepared 15 January 1997
Abstract * Foil Index for this file Addon

See also color IMAGE
Java versus JavaScript versus HTML Issues
Some Simple Motivating Examples
Language Features and Syntax
The Peculiar Object Model -- Functions Properties and Methods
Arrays in old and new JavaScript
Arguments of Functions
with and other object related syntax
The JavaScript built in Math String and Date Objects
The Navigator Objects -- Frames Windows Document Form
Event Handling including Function object
Cookies
User Objects and Examples including using JavaScript for frames

Table of Contents for full HTML of JavaScript Tutorial for CPS616 Technologies of the Information Age 1997


1 CPS 616 January-April 1997
Computational Science Track on Base Technologies for the Information Age:
Module on JavaScript

2 Abstract of CPS616 JavaScript Presentatation
3 General Remarks on JavaScript - I
4 General Remarks on JavaScript - II
5 Java / Interpreter Structure
6 Some Performance Comments
7 We need to know HTML!
8 Hello World Example of JavaScript- I
9 Hello World Example of JavaScript- II
10 Example of Clicking on a Form - I
11 Example of Clicking on a Form - II
12 Example of Parameterized HTML
13 LiveWire -- Netscape's Approach to CGI
14 Refinements in the <SCRIPT> Tag - I
15 Refinements in the <SCRIPT> Tag - II
16 JavaScript URL's
17 JavaScript Entities in HTML
18 JavaScript Compared to Java - I
19 JavaScript Compared to Java - II
20 The JavaScript Language -- Values, Names Etc.
21 The JavaScript Language -- Expressions - I
22 The JavaScript Language -- Expressions - II
23 The JavaScript Language -- Conditionals
24 JavaScript Object Model -- I
25 JavaScript Object Model -- II
26 Example of a JavaScript Function
27 Creation of JavaScript Objects
28 User Defined Objects Continued
29 The JavaScript with Statement for objects
30 The for ... in JavaScript syntax
31 The New Way of Defining Arrays
32 The old MakeArray Function and Arrays of Object
33 More on Arrays -- Properties and Multidimensions
34 The arguments Array in JavaScript
35 The this keyword in JavaScript
36 The parseInt parseFloat System functions
37 The eval JavaScript Function
38 Built-In JavaScript and LiveWire Objects
39 The Math and Number Objects in JavaScript
40 The String Object in JavaScript - I
41 Explanation of String methods - I
42 The String Object in JavaScript - II
43 Explanation of String methods - II
44 The Date Object in JavaScript
45 The Structure of the Navigator Object/Property Hierarchy
46 The Confused Window Labelling Scheme
47 The Window Hierarchy Pictorially
48 Creating New Windows
49 Role of Frames in JavaScript
50 Frame Basics in Netscape HTML -- Example
51 Frame Basics in Netscape HTML -- Rules
52 Use of Dummy Frames in JavaScript
53 General Syntax of <Frameset> </Frameset>
54 General Syntax of <Frame> tag
55 Event Handlers in JavaScript - I
56 Event Handlers in JavaScript - II
57 Event Handlers in JavaScript - III
58 Event Handlers in JavaScript - IV
59 The Function Object and Event Handlers
60 JavaScript Form Example
61 JavaScript Link Example
62 Structure of Index -- mainframe Case
63 setTimeout and clearTimeout
64 setTimeOut Example -- Display Current Time - I
65 setTimeOut Example -- Display Current Time - II
66 More on Document Objects -- Image
67 The Asynchronous JavaScript/Browser
68 prototype Property
69 Cookies - "hidden" alternative
70 Cookies -- Client Side Files
71 Specification of a cookie - I
72 Specification of a cookie - II
73 Use of Cookies in Server Program
74 Use of Cookies in Client Program
75 TAINTING! Security in JavaScript
76 LiveConnect Java to JavaScript - I
77 LiveConnect Java to JavaScript - II
78 Use of Dynamic Forms (Layout) in JavaScript
79 The flexbuttons dynamic form in JavaScript
80 Create RadioButtons Dynamically
81 Create Select Field Dynamically

This table of Contents Abstract



HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 1 CPS 616 January-April 1997
Computational Science Track on Base Technologies for the Information Age:
Module on JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Addon
See:
http://www.npac.syr.edu/users/gcf/cps616javascript97
Instructor: Geoffrey Fox
teamed with Meryem Ispirli, Nancy McCracken, Tom Scavo, John Yip
Syracuse University
111 College Place
Syracuse
New York 13244-4100

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 2 Abstract of CPS616 JavaScript Presentatation

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Addon
Java versus JavaScript versus HTML Issues
Some Simple Motivating Examples
Language Features and Syntax
The Peculiar Object Model -- Functions Properties and Methods
Arrays in old and new JavaScript
Arguments of Functions
with and other object related syntax
The JavaScript built in Math String and Date Objects
The Navigator Objects -- Frames Windows Document Form
Event Handling including Function object
Cookies
User Objects and Examples including using JavaScript for frames

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 3 General Remarks on JavaScript - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
Historically JavaScript was called LiveScript and developed by Netscape with some of the same goals as Java but focussed on a "smaller world" -- manipulation of text and options connected with Netscape Clients
TEXT ............................................. COMPUTER Language
HTML --> JavaScript Java <--- C++
Now we can use it under some circumstances as an alternative to Java where the "rapid prototyping" of a fully scripted language is helpful
  • We expect somebody to develop a fully interpreted Java -- equivalently to extend JavaScript to support more built-in objects (e.g. networking, images)
  • JavaScript is "either" active text (HTML) or a focused language!
JavaScript can be thought of as Java with the AWT (Abstract Windowing Toolkit) replaced by Netscape Client
  • JavaScript is a domain specific Interpreter for "Web Document Domain"
  • e.g. Postscript is a domain specific Interpreter for text layout and MATLAB is an interpreter for matrix manipulation, Mathematica is domain specific for mathematics ......

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 4 General Remarks on JavaScript - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
JavaScript particularly useful for multi-frame windows and for manipulating forms without complex CGI (Server Side) scripts
Here it can be much faster as purely client side whereas a CGI based form has inevitable delays as requires server-client communication and invocation of a new process on server side.
  • Java shares this advantage
This client side processing speed can be essential in some applications as users would not accept long delays (several seconds) on "trivial" mouse clicks
Java is a broad industry standard with a careful well documented design
JavaScript comes from Netscape but is supported by Microsoft.
  • It has a poorly documented (and thought through ?) basic design

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 5 Java / Interpreter Structure

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
Typical Java Applet Structure
  • Java Source ---> javac compiler --> JavaVM Universal machine code in .class file
  • Store JavaVM .class files on Web Server
  • Download JavaVM from Server to Client.
  • Interpreter built into browser, reads JavaVM and executes on client
Typical JavaScript Structure
  • JavaScript source is included in HTML text
  • Combined JavaScript and HTML is downloaded and interpreted by browser on client to produce HTML page
  • Particular user actions on HTML page (e.g. mouse clicks and form entries) can invoke JavaScript functions on the client
  • As browser one must "understand" raw high level language, this is substantially slower than interpreting JavaVM where "just" need to map universal machine code into machine code for a particular computer
Note in each case , Java and JavaScript use "runtime" which is "compiled high performance library" (probably written in C and C++)

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 6 Some Performance Comments

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
Execute C code Instruction -- 1 clock cycle ( 10^8 per second)
Run a client side C subroutine -- can do upto 10^6 instructions in time (few milliseconds) that is significant for user
JavaVM Interpreter -- roughly 50 times slower than C
JavaVM Just in Time Compiler (effectively compile JavaVM in real time) -- roughly 2 to 8 times slower than C
Native Java Compiler -- same speed as C
Perl Interpreter (but does process whole program before interpreting) -- 500 times slower than C except in runtime
Tcl, JavaScript "true" Interpreters - 5000 times slower than C
  • Can still do 100-1000 instructions in time that users don't notice!
Contact Host via CGI script -- Server, Network and Client HTML page regeneration delay can be measured in seconds.

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 7 We need to know HTML!

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
Note like most interpreters (look at Basic manual) JavaScript has a huge and growing number of "basic" methods and objects
To study JavaScript, we will have to use some relatively advanced HTML features including
  • Frames
  • Forms -- especially event handlers
  • Cookies

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 8 Hello World Example of JavaScript- I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index
<HTML>
<HEAD>
<Title>A Test of JavaScript</Title>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript" >
<!-- A Conventional comment to hide JavaScript from old browsers
document.writeln("<h1>Hello World!</h1>");
//scriptend-->
</SCRIPT>
<b>Continue with conventional HTML</b>
</BODY></HTML>

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 9 Hello World Example of JavaScript- II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Addon
There is only one real JavaScript statement here -- namely
document.writeln("textstring");
This outputs into current page the text in quotes followed by a newline
And note the rather peculiar way we "hide" JavaScript from browsers that can't understand it by enclosing in convential HTML Comment syntax
<SCRIPT LANGUAGE="JavaScript" >
<!-- A Conventional comment to hide JavaScript from old browsers
...... Bunch of JavaScript Statements .......
//scriptend-->
</SCRIPT>
Note depending on your needs, JavaScript can be in Header or Body section of document

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 10 Example of Clicking on a Form - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index Addon
<HTML><HEAD><TITLE>Javascript with Forms</TITLE>
<SCRIPT LANGUAGE="JavaScript" >
<!-- A Conventional comment to hide JavaScript from old browsers
function compute(form) {
if( confirm("Is this what you want?"))
form.result.value = eval(form.expr.value);
else alert("Enter a new expression then!"); }
//scriptend-->
</SCRIPT></HEAD>
<BODY><FORM>
Enter An Expression:
<INPUT TYPE="text" NAME="expr" SIZE=15>
<INPUT TYPE="button" VALUE="DoIt!" ONCLICK="compute(this.form)">
<BR>Result:
<INPUT TYPE="text" NAME="result" SIZE=15>
<BR>
</FORM></BODY></HTML>

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 11 Example of Clicking on a Form - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index
Enter An Expression: 9+5
Result: 14
confirm is a native Javascript method popping up a window, requesting confirmation of requested action
alert is a native Javascript method popping up a window with a message requiring user to place OK to get rid of.
onclick="Javascript Statement Block" naturally executes statement(s) when button clicked

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 12 Example of Parameterized HTML

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index Addon
<HTML><HEAD><TITLE>Javascript for Parameterizing HTML</TITLE>
<SCRIPT LANGUAGE="JavaScript" >
<!-- A Conventional comment to hide JavaScript from old browsers
var imagewidth=600; // These could be changed by form input or some
var imagefile="npac.gif"; // computation based on size of window etc.
//scriptend-->
</SCRIPT></HEAD>
<BODY> ......Bunch of Normal Stuff
<SCRIPT LANGUAGE="JavaScript" >
<!-- A Conventional comment to hide JavaScript from old browsers
document.writeln('<img align=top width=' + imagewidth + ' src="' + imagefile + '" >');
//scriptend-->
</SCRIPT>
.... Yet More Normal Stuff
</BODY></HTML>
Note single quotes used for JavaScript, Double quotes for HTML -- can use \' if necessary to hide special meaning from JavaScript

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 13 LiveWire -- Netscape's Approach to CGI

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index
Netscape Servers now support the "LiveWire" Extension which allows you to write "CGI Programs" in JavaScript

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 14 Refinements in the <SCRIPT> Tag - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index
One can specify the different versions of the Language
  • e.g.:
  • <SCRIPT LANGUAGE="JavaScript1.1"> Ignored by Netscape Navigator 2.0
  • location.replace("versionofpagefornav3.0.html");
  • </SCRIPT>
  • <SCRIPT LANGUAGE="JavaScript1.0" > Read by Netscape Navigator 2.0
  • ..........
location.replace(URL) replaces current page with new URL which in this case is assumed to hold a version with nifty new JavaScript 1.1 features

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 15 Refinements in the <SCRIPT> Tag - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index
This foilset assumes JavaScript 1.1 except in few cases such as Arrays where we also describe older 1.0 syntax.
<NOSCRIPT> .... </NOSCRIPT> Specifies what to do if user has disabled JavaScript in Options Menu (due to security perhaps!)
One can read JavaScript from a file
<SCRIPT SRC="JSLibrary.js">
document.write("Included File JSLibrary.js not found"); // The Navigator executes this stuff ONLY if JSLibrary.js is NOT found and so do not include useful stuff here!
</SCRIPT>
The included file must have .js suffix and server must be set up with correct MIME types to download .js files

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 16 JavaScript URL's

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index Addon
One can demonstrate JavaScript as an interpreter by typing JavaScript: into location text bar of your browser.
  • This gives a two frame window where you can directly type JavaScript and see response
One can use a similar capability in HREF and other atrribute definitions
  • <a href="javascript:history.go(-1)">Go Back One Step</a>
  • This loads the last page visited in being clicked
  • Using history.go(0) would reload current page
The JavaScript Manual describes some interesting Image Map Examples including:
  • <MAP name="buttonbar">
  • <AREA shape="rect" coords="0,0,16,14"
  • HREF="javascript:top.dosomething();
  • top.frames[1].location='URLtobeloadedintoanotherframe.html';" >
  • </MAP>

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 17 JavaScript Entities in HTML

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index Addon
One can parameterize HTML using document.write(ln) commands such as:
document.writeln("string1" + JSvariable +"string2"); // etc.
A "lighter weight way of achieving this can be illustrated by direct HTML syntax with NO <SCRIPT> tag and no document.write
<IMG WIDTH="&{JSvar1};" SRC="&{JSvar2};" >
where JSvar1 and JSvar2 are JavaScript variables holding width and URL of image
Syntax is modeled on that for for special characters
  • &GT; is > etc.
Such JavaScript Entities can ONLY appear on RIGHT HAND side of attribute values
  • Cannot appear in HTML text such as titles.
  • document.writeln approach has no such restriction!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 18 JavaScript Compared to Java - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
JavaScript: Interpreted and not compiled by Client or Server
Java: Compiled bytecodes downloaded from server and interpreted or (Just in Time) compiled by client
JavaScript: Object based but no classes or inheritance
Java: Object-Oriented. Applets consist of object classes with inheritance
JavaScript: Code typically integrated with or embedded(Entities) in HTML (SRC="File.js" is exception)
Java: Applets distinct from HTML and accessed by Applet Tag from HTML page

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 19 JavaScript Compared to Java - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
JavaScript: User has full access to capabilities of Netscape Navigator in functionality of window components
Java: User relies on Java AWT (or potentially HotJava browser) for features of Window Components
JavaScript: No explicit data types (just var) --- loose typing
Java: Variable data types must be declared and carefully "cast" to convert -- strong typing
JavaScript: Dynamic Binding. Object references are interpreted at runtime (typical interpreter)
Java: Static Binding. Object references must exist at compile time.
Security: Both JavaScript and Java applets as implemented today have significant security restrictions. This is a (Netscape) Runtime and not a language feature!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 20 The JavaScript Language -- Values, Names Etc.

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
JavaScript only has one simple type -- namely:
var anumber = 137; // or the SAME type var
var astring = "1"; // to define a string
The loose typing in JavaScript, allows interpreter to creatively interpret an expression and default (this is change from early documentation which claimed type taken from leftmost variable) is that strings have precedence over numbers so that for instance:
x = astring + anumber; // results in x = "1137"
use parseInt and parseFloat to extract numerical values from strings (see later)
Note special value null (no quotes) can be used as a null value
Strings can be delimited by '..text..' or "..text.." which are identical in meaning (unlike PERL) and one can use \n for newline and \t for TAB
Boolean literals are either true or false
Comments are /* any stuff including newlines */ or
Javascript statements; // This is a comment until new line

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 21 The JavaScript Language -- Expressions - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
JavaScript expressions and basic operators are similar to C PERL and Java
Assignment Operators are = += -= *= /= %= <<= >>= >>>= &= ^= |=
  • with x += y; meaning x= x + y;
  • and x %= y; meaning x = x%y; // x mod(y)
Conditional Expressions
  • status = (age >= 18) ? "adult" : "minor"; // sets status to be "adult" if age is larger than or equal to 18. Otherwise it is set to "minor"
Arithmetic operators are as usual with in addition ++ and --
  • y = ++x; // increments x by 1 and sets y to be final value of x

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 22 The JavaScript Language -- Expressions - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
Bitwise logical operators & (AND) | (OR) ^ (XOR) operate on the two numbers expressed in 32 bit integer form and perform indicated logical operation on each bit separately
<< is bitwise left shift discarding bits at left (high order) and zero filling at right
>> is bitwise right shift propagating the sign bit in high order (oposition 31)
>>> is zero fill right shift with no special treatment of sign bit
Boolean operations are && (AND), || (OR), ! (NOT) and can only operate on boolean variables which are true or false
Comparison Operators are == > >= < <= != which can be used on numerical OR string variables
Concatenation operator + joins two strings together
  • Note + is called . in PERL
x= "Hello "; y= "World!";
x + y is "Hello World!"

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 23 The JavaScript Language -- Conditionals

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
These are roughly a subset of those in Java
if statements cannot use else if and must have statements to be executed placed in curly braces unless only one statement
if( condition ) {
Need curlies if more than one statement here; }
else { // Optional of course
Statements which can contain nested if's; }
for and while are essentially as in Java
for( initial expression ; condition; increment expression ) {
statements to execute; }
while(condition) {
stuff to do as long as condition true; }
break can appear in for or while loops and causes control to pass to statement after end of for or while loop. Named break's as in Java or PERL are not supported
continue in a for or while loop skips over remaining statements in body and goes to next iteration of each loop

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 24 JavaScript Object Model -- I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Addon
JavaScript has a simple object oriented structure without any inheritance ( a major difference from Java)
JavaScript has a rather confused syntax for defining objects which mixes the role of Class definition, function and constructor!
An object is a container which has variables (simple datatypes) other objects or methods inside it.
Variables or other objects inside an object are called properties
functions inside an object are called its methods
Arrays are defined as sequential properties inside a particular object
Multidimensional arrays are constructed as object arrays which themselves have properties which are arrays.

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 25 JavaScript Object Model -- II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Addon
variables can be written in a fashion such as:
parentobject.property1[index1].property2..finalproperty[indexN]
Note there is no hierarchical inheritance in definition of objects but the ability to define object properties that are themselves objects creates a natural hierarchical naming scheme
Object Methods are naturally referred to as
object ...property.method(arguments)
Methods Objects and Properties are naturally divided into those defined by Netscape and those defined by user.
Here is an example of a Netscape object with a typical property and method
  • document is a Netscape object typically defined by a .html page
  • document.writeln is method of this object which outputs string followed by a newline
  • document.location is a property of this object containing its URL

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 26 Example of a JavaScript Function

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
top.setframe("help.html","maindisplay");
function setframe(relativeurldesired,framelabel) {
  • var actualurl = top.baseurl + relativeurldesired;
  • top.frames[framelabel].location.href = this.actualurl;
}
top is a Netscape(Navigator) object with a property frames which is an array labelled by either integers or by value of name attribute in <frame> name="textofframelabel" </frame> tag
Setting a URL into location.href property of a frame loads that page into given frame.
top labels functions defined in page that defines frames
use this.actualurl to distinguish function's variable actualurl from a global variable of same name
Put these functions in <head> </head> section so as to ensure they are loaded before anything else

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 27 Creation of JavaScript Objects

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
You define the Class template (to use a Java lingo) with a function definition
Then create an instance of the object with the new statement which acts as a constructor to initialize values
function MakeMenu(no,name) {
this.no = no; // Give instance a numerical label
this.name = name; // Label this particular menu
this.color = 'black';
this.menuselection = 1;
this.count =0;
this.options = new Array(); // We will discuss this later
}
worldmenu = new MakeMenu(1,'world');
familymenu = new MakeMenu(2,'family'); // define two menu instances

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 28 User Defined Objects Continued

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
You can access object properties in a natural fashion such as:
var actualselected = worldmenu.menuselection;
familymenu.color = 'red';
Curiously you can also use in Netscape 2 an array like notation to which we will return:
familymenu[0] is same as familymenu.no
familymenu[1] is same as familymenu.name etc.
We will return to this when we discuss arrays
One can associate methods with user objects but with a syntax that appears very limiting as object methods have identical arguments to function
General Syntax is:
Objectname.methodname = functionname;
where Objectname is an existing Object and functionname is an existing function -- it can be used to set event handlers with no arguments!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 29 The JavaScript with Statement for objects

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
with ( ParticularObject ) {
..Any old statements ..
}
// Within these curly braces, ParticularObject is assumed to be default object for any property or method that does not specify a parent object
with (Math) { // An example
area = PI *r*r; // PI is in Math object
x= r * cos(theta); // cos is method in Math Object
y= r * sin(theta); // sin is a method in Math Object
}

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 30 The for ... in JavaScript syntax

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
This allows one to iterate over all the properties of an object
for ( variable in object ) { // Generic Form
Bunch of statements }
function dump_props(obj, obj_name) {
var result = "";
for( var i in obj) {
result += obj_name + "." + i + " = " + obj[i] + "<BR>"; }
result += "<HR>";
return result;
}
Here i runs over names of Properties and obj[i] is actual property
Note user supplies obj and obj_name
function car(make,model) { // An Example
this.make = make;
this.model = model; }
mycar = new car("Ford","Explorer");
document.writeln(dump_props(mycar,"mycar"));

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 31 The New Way of Defining Arrays

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
Write var area = new Array(); // Introduced in Netscape 3
and then you can set as described in Netscape Press book on JavaScript
area[0] = "Alabama";
area[1] = "Alabama";
area[2] = "Alaska"; // etc.
acode[0] = 205;
acode[1] = 334;
acode[2] = 907; // mappring area codes to states
area.length is automatically set as length of array ( 3 in this case)
Note you can set array elements to be objects to make Arrays of objects
e.g. listofmenus = new Array();
listofmenus[0] = new menuobject(1,'world');
worldmenu = listofmenus[0]; // A synonym

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 32 The old MakeArray Function and Arrays of Object

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
This is the old way of defining arrays and only way allowed in Netscape 2.
You were asked to define a special function
function MakeArray(size) {
this.length = size;
for( var i=1; i<=size; i++ ) {
this[i]= 0; }
}
This gives arrays where you must predefine a size (a problem) and where arrays count from 1 not 0 (an artifact of MakeArray setting this.length = size at start not end of function. The latter feature could lead to great joy for Fortran programmers!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 33 More on Arrays -- Properties and Multidimensions

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
Note one can easily define and use multidimensional arrays as in syntax
  • listofmenus[0].options[0]='Admin';
  • var currentworld = 0;
  • listofmenus[currentworld].options[1]='FoilWorld'; // etc.
Arrays (the new ones!) have some interesting methods
  • MyArray.sort(sortmethod) returns list sorted in fashion determined by optional argument sortmethod (a user function comparing two elements)
  • MyArray.join(separator) returns a string of the MyArray elements separated by the character string separator
  • MyArray.reverse() reverses order in Array
MyArray = new Array(Initialsize,value0,value1, ...); // can specify an initialsize and initial values at the user's pleasure. These arguments are opitional and undefined initial values are set to null

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 34 The arguments Array in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
function anyoldname(x1,x2) {
var argv = anyoldname.arguments;
n = anyoldname.arguments.length; // number of arguments -- same as argv.length
var y1 = anyoldname.arguments[0]; // y1 is same as this.x1 or argv[0]
var yn = anyoldname.arguments[n-1]; // last argument -- same as argv[n-1]
var wherefrom = anyoldname.caller; // use inside function to find where called from
}
This allows one to find number of arguments when called and process functions with variable number of arguments
Netscape documentation says this is a property of Functions (interpreted functions) but appears to work on both!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 35 The this keyword in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
this keyword can be very important but it is also confusing as not clear what it refers to at times.
  • Also not always clear when needed
Here is an example of use to set URL for a link
function seturl(obj) { // Put in <head></head> Part of document
obj.target = "Desiredframe"; // set frame you want it to go in!
obj.href="http://www.npac.syr.edu"; // or calculate URL dynamically
}
In normal HTML page place:
<a href="" onClick="seturl(this)" onMouseOver="window.status='URL set dynamically in routine seturl';return true" >Click Here for Dynamic URL</a>
Here this refers to link object created by <a ..> </a>
window.status is line at bottom which usually records URL
Note can specify nontrivial href and onClick but if onClick specifies href property it overrides that in HTML page

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 36 The parseInt parseFloat System functions

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
These are system functions ( not string methods) that convert strings to numbers
parseInt("15") or equivalently parseInt("15",10) both return the number 15
The optional second argument is radix so that parseInt("15",8) returns 17
If input string begins with "0x" the default radix is 16 (hexadecimal) whereas if it begins with "0" the radix is 8 (octal) -- otherwise default radix is 10
x = 1 +"1"; // evaluates to "11" whereas
x = 1 + parseInt("1"); // evaluates to 2
parseFloat(string) returns floating point equivalent of string
  • var x = "0.0314E+2"; var y = parseFloat(x); // sets y = 3.14
on platforms that support it, parseInt and parseFloat will return NaN (Not a Number) when argument is inappropriate

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 37 The eval JavaScript Function

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
eval is an important function as it allows you build Javascript dynamically
For instance document.forms[0].actualtextname.value is value of form element specified as
<INPUT TYPE="text" NAME="actualtextname" VALUE="value" onChange="handle(this.name)" >
this.name holds actualtextname but as an ascii string which cannot be directly be used in
var x = document.forms[0].actualtextname.value;
var x = eval("document.forms[0]." + actualtextname + ".value"); // works!
eval applies JavaScript interpreter to argument and then re-interprets as shown above
This can be used to copy information between forms as in
eval("document.forms[1]." + actualtextname + ".defaultvalue") = eval("document.forms[0]." + actualtextname + ".value")
eval did not work properly for a long time! -- Please check on your browser

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 38 Built-In JavaScript and LiveWire Objects

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Secs 74.8
JavaScript has its distinctive built-in objects associated with navigator (window, document etc.) and server (for LiveWire)
There are also currently seven other built in types of objects in JavaScript which are in LiveWire as well
  • Array, Boolean, Function, Date, Math , Number, String
We have described Array and will ignore Boolean
We will review the others in following

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 39 The Math and Number Objects in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 63.3 Addon
Math has a set of properties(built in constants) including
E LN10 LN2 PI SQRT1_2 SQRT2 so that
Math.PI = 3.14159 etc.
Math methods include the usual ones in Fortran Intrinsic library with examples
Math.random() returns pseudo random number between 0 and 1
Math.abs(x) returns absolute value of x
Math.max(x1,x2) returns maximum of two numbers x1 and x2
Math.cos(x) returns cosine of argument x in radians
Math.round(x) rounds x to nearest positive or negative integer
The Number object has properties defining system dependent constants such as:
  • Number.MAX_VALUE is Largest representable number on your machine
  • Number.NaN represents "Not a Number" used by parseInt and parseFloat

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 40 The String Object in JavaScript - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 66.2
Any constant such as "Hello World!" or variable holding text is a string object in JavaScript -- here is the first example
/* Add stem to newurl if latter is a relative address */
/* stem must end with a slash */
function checkurl(stem,newurl) {
  • var len = newurl.length; // length Property of string object
  • var stemlen = stem.length;
  • if( len < 7 ) {
    • return (stem + newurl); } // Input was not absolute
  • var grab = newurl.substring(0,6); // Get first six characters
  • if( (grab == "ftp://") || (grab == "http:/") )
    • return newurl; // input was definitely absolute
  • return (stem + newurl);
}
function seturl(name) {
name.href = checkurl("http://www.npac.syr.edu/users/gcf/wisdom/","List.html");
}

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 41 Explanation of String methods - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 66.2 Addon
the String object has one property with actualstring.length recording length in characters of string
Note we only have one type of string object -- Java has String (fixed) and StringBuffer (mutable)
characters are indexed from the left starting at 0 and ending with actualstring.length-1
newstring = actualstring.substring(index1,index2); // returns a string consisting of characters in locations index1 ... index2-1
Peculiarly if index2 < index1, substring returns locations index2 ... index1-1

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 42 The String Object in JavaScript - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 73.4
/* take two linked comma separated strings containing parameter names and
values for an Applet and produce correct HTML definition of them */
function commaseparated(appletpname,appletpvalue) {
var stop = appletpname.lastIndexOf(','); // last occurrence of ,
if( appletpname.length <= 0 ) stop = -2; // length is only property of string object
index = -1;
var ct = 0; // this is just a precaution
var jndex1 = 0;
var jndex = -1;
while( index <= stop) { // scan through commas
index1= appletpname.indexOf(',',index+1); // next occurrence of ,
if(index1 < 0 ) index1= appletpname.length; // no more ,'s
++ct;
if(ct >20 ) break;
jndex1 = appletpvalue.indexOf(',',jndex+1);
if(jndex1 < 0 ) jndex1= appletpvalue.length;
grab1 = appletpname.substring(index+1,index1); // Extract the stuff between commas
grab2 = appletpvalue.substring(jndex+1,jndex1);
top.document.writeln('<param name=' + grab1 + ' value="' + grab2 + '">');
index=index1;
jndex=jndex1; }
}

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 43 Explanation of String methods - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 76.3
This example introduces two new methods
actualstring.IndexOf(lookfor); // where lookfor can be any string or property holding a string
This returns index in actualstring where character in actualstring starts a substring that exactly matches lookfor
"http://www.npac.syr.edu".IndexOf("www"); // returns 7
actualstring.IndexOf(lookfor, searchfrom); // searchfrom is the index where search starts -- in example where we scan for commas, searchfrom is set to be one more than location where last comma found
IndexOf and lastIndexOf return -1 if requested string cannot be found
actualstring.lastIndexOf(lookfor, lastsearchfrom); // is just like IndexOf but starts from the end not the beginning of the string
default value of lastsearchfrom is actualstring.length-1

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 44 The Date Object in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 54.7 Addon
JavaScript really needs the powerful text processing capabilities of PERL -- Lets hope either Netscape adds them or somebody builds these functions
On the otherhand JavaScript like Java has an amazing number of capabilities associated with the Date object including 21 builtin methods
today = new Date(); // sets today to current Date and Time
asiwrite = new Date("February 26, 1996 15:13:00"); // sets asiwrite to date and time that these notes were prepared!
Note both Java and JavaString store dates internally as number of elapsed milliseconds since January 1,1970 00:00:00.
In a Java lookalike, Date.UTC(date as bunch of numbers) and Date.parse(date as a text string) are "class or static" methods
There are methods such as getMonth which extracts month from a date
See the online resource for all possible methods!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 45 The Structure of the Navigator Object/Property Hierarchy

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index Secs 84.9
Note window is basic concept and frames are children of window of same object type

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 46 The Confused Window Labelling Scheme

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Secs 148.3
Typical property top.frames[name or number].document.
forms[ index and not name ].elementname.value illustrates hierarchy going from top to bottom as one goes from left to right
One can also use framename instead of frames["framename"] -- latter is very much more convenient as can access more easily as variable frame in JavaScript code
  • If eval works, one can use this to generate framename
navigator window and frame are objects defining hierarchy of cascading containers
document form history link location are objects defining parts of a window or frame.
anchors links forms frames applets images are array properties
top parent self are properties labelling particular frames and windows
Note these are all defined within a single browser window
opener is a property of a window defining the window of document that called window.open to instantiate this window

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 47 The Window Hierarchy Pictorially

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index Secs 105.1
top is frameset containing three grey windows while parent is one with three red frames
childw is frameset in new browser window which is brown

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 48 Creating New Windows

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 93.6
The window object has a method open which allows one to create entirely new windows which are equivalent to cliocking "New Web Browser" on Netscape File Menu
childw = window.open(URL,Largely_Irrelevant_Name, Quite_Important_Features);
The last argument is a set of comma separated options such as
  • toolbar = yes [no]
  • location = yes [no] (display a location bar or not)
  • resizable = on [off] (allow resizing of window)
  • status = yes [no] (display status bar at bottom)
  • menubar = yes [no]
  • directories = yes [no] (display the not so useful directories bar)
  • scrollbars = yes [no] (allow or not scrollbars if needed)
  • width = W; (number of pixels in window width)
  • height = H; (number of pixels)
Javascript in spawned window can access properties of originating window as top.opener

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 49 Role of Frames in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Secs 80.6
Frames are very relevant to JavaScript because not only can JavaScript help the various frames talk to each other but also one sometimes needs dummy frames to preserve JavaScript between pages
In Java AWT we learnt about hierarchical layout schemes -- in Netscape 2.0 world the containers in which subcomponents are laid out are frames and forms within frames.
  • In Layout Manager language, Netsape uses HTML syntax to control layout
  • HTML is more powerful than mechanisms in AWT Layout Managers?

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 50 Frame Basics in Netscape HTML -- Example

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 97.9 Addon
<HTML>
<HEAD>
Bunch of JavaScript
</HEAD>
<FRAMESET ROWS="10%,80%,10%" >
<FRAME SRC="topbanner.html" >
<FRAMESET COLS="30%,70%" >
  • <FRAME SRC="index.html">
  • <FRAME SRC="Mainstuff.html">
</FRAMESET>
<FRAME SRC="bottombanner.html" >
</FRAMESET>
<NOFRAMES>
<h2> This Page needs frames -- please find a kinder URL</b>
</NOFRAMES>

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 51 Frame Basics in Netscape HTML -- Rules

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Secs 66.2
A document that contains a FRAMESET must NOT have a BODY tag and so normal HTML tags cannot appear in a document that defines these containers
One needs an end </FRAMESET> tag for each <FRAMESET> but no end tag for <FRAME>'s
Note JavaScript can appear in header of a document defining frames and these JavaScript properties and methods can always be accessed (in read or write mode) by documents inside frames by refering to as top.property/method
Anything inside <NOFRAMES> .... </NOFRAMES> container will be ignored by a Framess capable browser (such as Netscape 2.0) and output by one that cannot produce frames such as Netscape 1.X

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 52 Use of Dummy Frames in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 93.6
<HEAD> Bunch of JavaScript</HEAD>
<BODY>
Sundry actions that load a new URL into page
</BODY>
will result in loss of all JavaScript methods and properties as you load new page! This can be avoided by using dummy frames as below
<HEAD> Bunch of JavaScript</HEAD>
<FRAMESET ROWS="1,*" >
<FRAME NAME="DUMMY" >
<FRAME NAME="ActualFrame" SRC="Thiscontainsoldbodyhtml.html" >
</FRAMESET>
Now use target="ActualFrame" in <a href="URL"> and reloading ActualFrame will NOT destroy your JavaScript!
Note we defined a dummy frame which occupied one pixel (could use zero!) above ActualFrame
The * notation tells Netscape to assign the remaining rows to second frame

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 53 General Syntax of <Frameset> </Frameset>

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 92.1
<Frameset Rows="rowlist" Cols="collist" >
Each of rowlist and collist must be null or comma separated values defining Nrow by Ncol frames -- typically one of these is unity as one uses hierarchical Framesets to get a nonuniform grid
Following <Frameset> there must be the correct number of frames defined either by a <Frame> tag or by <Frameset></Frameset> hierarchical definition
rowlist and collist can be comma separated mixture of
  • absolute number such as 100 specifying pixels to be allocated
  • percentage such as 30% specifying percentage of available space
  • * notation where a single * means all the remaining space
  • rows="50,2*,*,*" means first frame gets 50 pixels while remaining 3 frames get 50%,25%,25% respectively of remaining space

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 54 General Syntax of <Frame> tag

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 46
<frame Src="URL" Name="framename" Noresize scrolling=YES|NO|AUTO Marginwidth="value" Marginheight="value" >
All of these are optional -- the URL defined by Src attribute is document to be loaded into this frame -- this is often blank as user or other JavaScript code will specify what to load using TARGET="framename" in a link (<a > or equivalent)
The value of Name attribute is used by target and is essential if you want to be able to load into this frame from the outside. A link inside this frame will load into this frame if no taget specified
Noresize if present says that user canNOT resize this frame -- this has impact on ability of related frames to be resized
Marginwidth and Marginheight are given in pixels to specify the margin to be used around the frame
scrolling=YES will always give frame scrollbars
scrolling=NO will give no scrollbars and truncate document if necessary
scrolling=AUTO allows Netscape to choose if scrollbars are appropriate

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 55 Event Handlers in JavaScript - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Secs 46 Addon
There are four major types of events which you can add event handlers
  • Form related events
  • links
  • Loading and Unloading new window
  • Loading Images and Browsing Image Maps
These are new (to traditional non JavaScript HTML) attributes inside those tags which traditionally respond to Mouse clicks or movement (or possibly text input)
One can set event handlers in two ways described on following page

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 56 Event Handlers in JavaScript - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Secs 84.9
You can set event handlers within HTML TAG using syntax like
  • onclick="whattocall(arg1,arg2...)"
Alternatively set event handler explicitly with
  • document.myform.mybutton.onclick=anotherfunction; // where anotherfunction is a function without arguments and there are NO () in this syntax but you must have () when specifying inside TAG
  • Also note JavaScript is case sensitive and onclick is ALL lower case here but in HTML which is not case sensitive you are free to use any case in ONclicK= " .. " syntax

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 57 Event Handlers in JavaScript - III

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 96.4
onUnLoad event handler is called when you exit a particular page
onLoad event handler is called when you load (or reload on returning to page) a new page
  • <body onLoad='alert("You have just seen my first JavaScript Program Loaded!")' .. other body tags ... >
onAbort -- Images -- handler called when user aborts loading of image by for instance clicking stop button
onError -- Images and windows -- called when document or Image loading causes an error
onFocus -- windows, frames, and all elements in forms -- handler called when Mouse lies in scope of a window/frame or particular form field
onBlur is opposite of onFocus and corresponds to Mouse leaving scope of those form fields (or window, frames)

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 58 Event Handlers in JavaScript - IV

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 80.6
onClick -- button,checkbox,radio,reset,submit in form and links specified by <a > -- handler called when item clicked
onChange -- select,text,textarea in forms when change occurs in these fields
onMouseOver -- plays same role for link that onFocus does for form elements
onMouseout -- opposite of onMouseover for links and also set when user moves mouse pointer outside area defined by image map
onSelect -- text or textarea in forms -- handler called when text selected
onSubmit -- forms -- handler called when submit button on form clicked
onReset -- forms -- handler called when user resets a form

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 59 The Function Object and Event Handlers

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 96.4
One can define a string of JavaScript to be compiled as a function with syntax
Target = new Function( [arg1,...argn], functionBody)
where the optional arg1,...argn are arguments for formal function defined in functionBody
Target is either the name of a variable or a property of an existing object or an event handler such as window.onerror
var setBGcolor = new Function("document.bgColor='antiquewhite'");
so you can now execute setBGcolor() where the function can be changed at any time with another setBGcolor = new Function("document.bgColor='pink'");
One can define dynamic event handlers which as described MUST be lower case and MUST have no arguments
  • window.onfocus = setBGcolor;
Note like eval, functionBody can be JavaScript constructed dynamically as in
  • var dynamic = 'bgcolor';
  • Function("document." + dynamic + "='antiquewhite'");

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 60 JavaScript Form Example

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Secs 37.4
<form>
To test tree of knowledge
<input type="text" name="data" size=30 onFocus="window.status='this is a Test of onFocus'; return true">
<input type="button" value="clickit!" onClick="top.dosomething('This is a Test of onClick')" >
</form>
This shows a couple of simple form elements with onFocus and onClick illustrated
window.status is property holding message at bottom of browser window
One would typically have onChange handler as well in text field. Note that with these handlers one does NOT need server side CGI script to process form

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 61 JavaScript Link Example

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 67.6
<a href="" onClick="top.seturl(this,'nextitem27.html')" onMouseOver="window.status='this is a Test of onMouseOver'; return true">Exciting Item 27</a>
Note this very typical use of onClick in <a > link.
this is current link and of object type location.
set href to be anything including "" -- don't leave out otherwise won't be a link -- will be anchor instead -- this insures that link blue!
set href and target frame in onClick Event handler
This is is how you get indices to work
  • put seturl in top document defining frames
  • <a > links are in index frame and onClick there allows seturl to load required document into mainframe -- the main display frame
function seturl(linkname,fileurl) {
linkname.target="top.mainframe";
linkname.href = fileurl); }

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 62 Structure of Index -- mainframe Case

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index Secs 33.1
Top document has JavaScript in <head> </head> and defines <frameset></frameset> split in two by columns

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 63 setTimeout and clearTimeout

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 96.4 Addon
These are methods of a given window or frame
yourID = setTimeout(JSexp, timeinmsecs);
sets yourID to a handle which can be used in
clearTimeout(yourID); // which completely clears what was started by setTimeout
setTimeout starts a timer which causes JavaScript expression JSexp to be evaluated after a time interval of timeinmsecs which is expressed in milliseconds
Time outs can be used to animate text or images and make a display change at after a given interval
  • Also to start a daemon monitoring whats going on!
Note setTimeout does not start a LOOP -- just a single timing.
Thus clearTimeout need NOT be called unless you want abnormal termination
Further if you want a loop, please ensure JSexp restarts a new setTimeout

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 64 setTimeOut Example -- Display Current Time - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 93.6
<SCRIPT>
var timerID = null; // will be returned by call to setTimeout
var timerrunning = false;
function stopclock() { // terminate timeout
  • if( timerrunning )
    • clearTimeout(timerID);
  • timerrunning = false; }
function startclock()
{ // terminate timeout, display time, start timeout
  • stopclock();showtime(); }
function showtime()
{ // display time, start timeout
  • // Calculate current time in timeValue
  • document.clock.face.value = timeValue;
  • timerID = setTimeout("showtime()",1000); // Update every second
  • timerrunning = true; }
</SCRIPT>

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 65 setTimeOut Example -- Display Current Time - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Secs 56.1
The previous JavaScript goes in header of document whose body is:
<BODY onLoad="startclock()" >
<FORM name="clock" onSubmit="0" >
  • <input type="text" name="face" size=12 value="" >
</FORM>
</BODY>
Note <FORM> only used for output using
  • document.clock.face.value
onload function called when page is loaded and this starts timer.

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 66 More on Document Objects -- Image

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
The document object has several important subobjects including Anchor, Applet, Area, Form, Image and Link.
It also has arrays anchors, applets, forms, images and links arrays holding all the occurrences of these objects in a particular document.
We have illustrated Form and Link already -- here we look at Image
<IMG NAME="fred" SRC="jim.gif" > in an HTML file generates an object document.fred of type Image with property document.fred.src="jim.gif"
One can preload images using syntax like:
  • image1 = new Image(); image1.src = "henry.jpg";
  • and then change Image in document using
  • document.fred.src = image1.src;
  • henry.jpg is fetched from cache and so this is fast!
This technology can be used for animated images and also to quickly change a picture displayed in perhaps an online shop catalog where user chooses a new item in a form.

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 67 The Asynchronous JavaScript/Browser

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
There are several Issues that are a bit tricky due to asynchronous (thread based!) processing in Browsers
This is seen in reloading JavaScript pages. This produces unclear results as different frames and associated JavaScript variables are set in adifferent order from that in which multi-frame system was built!
  • Often get "false" errors as variables not set "in time"
Note that when you set location field in a window, with a JavaScript command such as:
  • window.location = "newurl";
Then following commands are executed immediately and do not wait wait for new page to be loaded!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 68 prototype Property

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Critical Information in IMAGE
Full HTML Index
This allows you to dynamically change object definitions
We used function(constructor)
  • function car(make,model) { // An Example
  • this.make = make;
  • this.color = 'red';
  • this.model = model; }
  • mycar = new car("Ford","Explorer");
Suppose we wanted to add a new property 4wheelstatus
  • car.prototype.4wheelstatus = false;
  • mycar.4wheelstatus = true;
We can add methods with
  • function repaint(newcolor) {
    • this.color = newcolor; }
  • car.prototype.repaint =repaint;
We can avoid repainting mycar by assigning
mycar.repaint = specialrepaint;
  • function specialrepaint(newcolor) {}

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 69 Cookies - "hidden" alternative

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
Cookies were introduced by Netscape to preserve client side state
If you have a CGI script that services several clients (ordering T Shirts perhaps), it is neatest to use client and not server to store information such as name of user, passwords etc.
Traditionally used as passed in forms using "hidden" fields
  • <INPUT type=hidden" name="user" value="" >
  • set by formname.user.value = WHATHAVEYOU;
Such hidden fields are passed to CGI scripts in same fashion as other variables set in form text fields
hidden values can either by set by JavaScript on client side or returned built into a page constructed by CGI script which might read N values and return a new form with M new fields for user and N old entries preserved in hidden fields
So hidden variables are nice but only preserved as long as you keep to page you started with or that returned by CGI script.

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 70 Cookies -- Client Side Files

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index Addon
Cookies provide an alternative mechanism where information is saved in special file on client (called cookies or cookies.txt)
  • Note History Cache Bookmarks are also saved client side
Such files can preserve information in a more robust way than hidden alternative!
Cookies are supported by Microsoft and and Netscape and can be used (like forms) for pure client-side or client-server activities
Neither hidden or cookies are very secure
Cookies have 5 attributes -- name, expires, domain, path and secure and are specified by a single line that must specify a value for name but where all other attributes are optional.

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 71 Specification of a cookie - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
name=value; EXPIRES=datevalue; DOMAIN=domainname; PATH=pathname; SECURE
name is required and tells you name of cookie
EXPIRES is optional but if present specifies a date afterwhich cookie is to be deleted
EXPIRES uses a modification of syntax returned by JavaScript function Dateobject.toGMTString(timevalueinseconds)
  • dayofweek, Day-Month-Year Hour:Min:Secs GMT
  • e.g. Wednesday 19-02-97 19:10:24 GMT
It appears that one can just use the slightly different syntax of toGMTString
  • so now = new DATE(); now.setTime( now.getTime() + 24*60*60);
  • now.toGMTString() will give an expiration date of one day from now!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 72 Specification of a cookie - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
DOMAIN defaults to domain of server where cookie set and general matching matching is done starting at end of domain
  • DOMAIN=npac.syr.edu matches all servers ending with these characters
PATH=/ is most general path and matches all paths but default is again path of document that set cookie.
  • Thus you must set PATH explicitly to / if you want cookie to be valid for a file stored in directory below that of setting document
SECURE if present requires a secure communication channel

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 73 Use of Cookies in Server Program

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
The Brower passes to server any cookies that are valid for a given page in HTTP header
Note only name=value is passed because PATH DOMAIN SECURE and EXPIRES are used to check if cookie should be passed
The server stores cookie strings in $HTTP_COOKIE environment variable as name1=value1; name2=value2;
  • It is easy for CGI script to decode this $HTTP_COOKIE environment variable
One can send cookies back to client using
Set-cookie: name1=value1; expires= .. ; domain= ...; etc.
before the
content-type: text/html header line

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 74 Use of Cookies in Client Program

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * Important Information in IMAGE
Full HTML Index
JavaScript string document.cookie holds cookies that are valid for this document and can be used to either set or retrieve cookie values
In example, we have a page with a form that sets values and stores for a certain length of time. This is entirely processed client-side with JavaScript interpreting form and storing values in appropriate cookie entries
These cookies are read on other pages (consistent with PATH and DOMAIN) and if present used to define JavaScript variables that are used in "parameterized HTML"
Note document.cookie is set to a single cookie value but when read gives all cookies for this document!

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 75 TAINTING! Security in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index Addon
Tainting ensures that certain properties cannot be freely used
These "taintable" properties include cookie, links, title etc in document; most interesting properties of forms; history; location
Once you access such a property from a SERVER different from that which spawned JavaScript page, then your current statement and everything derived from it is "tainted"
  • Note testing to see if a variable is tainted, taints your program and so one cannot write useful JavaScript programs involving tainted quantities and networking
tainted variables may NOT be passed over the Network to other servers e.g. to a CGI Script
You can control the tainting of pages and untaint them so that remote servers can freely use
  • However I don't think anybody does this ......

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 76 LiveConnect Java to JavaScript - I

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
LiveConnect is an important but still experimental capability that allows Java Applets to freely access JavaScript variables and vice versa
You can use this to call java methods in JavaScript noting that a java package X is called Packages.X in JavaScript
var myjavadate= new Packages.java.util.date(); // Creates a JavaScript variable from the java Date constructor
This development potentially gives us an Interpreted version of Java!
LiveConnect is only supported by Netscape at present
You can also change java variables in running applets as long as they are public (see next page)

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 77 LiveConnect Java to JavaScript - II

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
So if Applet HelloWorld has:
  • public void setString(String aString) {
    • javaslocalcopy = aString;
    • repaint(); }
Then you can change javaslocalcopy from JavaScript using
document.applet["HelloWorld"].setString(text stuff from JavaScript);
Care must be taken in typing and best is to convert everything explicitly to Strings in Java and JavaScript
  • Netscape needs to clarify this!
Correspondingly Java Applets can control Web Pages with JavaScript functions in them and so access capabilities of Netscape Browser explicitly
  • see NPAC TANGO System

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 78 Use of Dynamic Forms (Layout) in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
<head> ... <script language="JavaScript">
testbuttons = new top.MakeArray(2);
testbuttons[1]='one';
testbuttons[2]='two';
function testprocess(object1,object2,index) {
confirm(object1.name + ' ' + object2.value + ' ' + index); }
</script></head>
This can give a form created by JavaScript
<form name="testbuttonsform">
<script language="JavaScript">
top.flexbuttons(1,"testgroup",2,testbuttons,2,"testprocess");
</script>
</form>

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 79 The flexbuttons dynamic form in JavaScript

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
function flexbuttons(maxradio, groupname, number, indname, indexselected, onprocess)
/* Output a group of single selection radio or select buttons */
/* maxradio defines strategy -- if more than maxradio items use a select field, if smaller than this use radio buttons */
/* User responsible for <form> </form> container and any formatting */
/* onprocess is textstring of "onclick/change" function" */
/* number is number of buttons with name indname[1...number] */
/* groupname is name of group */
/* indexselected running from 1 to number is initial selection */

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 80 Create RadioButtons Dynamically

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
function flexbuttons(maxradio, groupname, number, indname, indexselected, onprocess) {
if( number <= maxradio) {
for( var i=1; i <= number ; i++) {
  • top.fred.document.writeln('<input type="radio" name="' + groupname + '" value="' + indname[i] + '"');
  • if( i == indexselected )
  • top.fred.document.writeln('CHECKED');
  • top.fred.document.writeln(' onClick="' + onprocess + '(this,this,' + i + ')" >');
} // end for loop
} // end radio button if statement

HELP! * GREY=local HTML version of LOCAL Foils prepared 15 January 1997

Foil 81 Create Select Field Dynamically

From JavaScript Tutorial for CPS616 Technologies of the Information Age 1997 Basic Information Track of CPS -- Spring Semester 97. * See also color IMAGE
Full HTML Index
else { // Case when enough options for a select field
top.fred.document.writeln('<select name="' + groupname + '" onChange="' + onprocess + '(this,this.options[this.selectedIndex],(1+this.selectedIndex))" >');
  • for( var i=1; i <= number ; i++) {
  • var ifselected = ' ';
  • if( i == indexselected )
  • ifselected = ' SELECTED ';
  • top.fred.document.writeln('<option ' + ifselected + 'value="' + indname[i] + '" >' + indname[i]);
  • } // End for loop
top.fred.document.writeln('</select>');
} // End else for generating select field
} // End of flexbuttons

Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu

If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.

Page produced by wwwfoil on Sat May 24 1997