HELP! * GREY=local Full HTML for

LOCAL foilset CPS616 Lectures on JavaScript

Given by Geoffrey C. Fox at CPS616 Basic Information Track for Computational Science on Winter-Spring Semester 96. Foils prepared 26 February 1996
Abstract * Foil Index for this file

See also color IMAGE
Some Simple Motivating Examples
Language Features and Syntax
The Peculiar Object Model -- Functions Properties and Methods
MakeArray and how to fool Interpreter into Arrays
Arguments of Functions
with and other object related syntax
The Math String and Date Objects
The Navigator Objects
Event Handling
User Objects and examples including using JavaScript for frames

Table of Contents for full HTML of CPS616 Lectures on JavaScript


1 CPS 616
January-April 1996
Computational Science Track on base technologies for the Information Age:
Module on JavaScript from Netscape

2 Abstract of CPS616 JavaScript Presentatation
3 General Remarks on JavaScript
4 Hello World Example of JavaScript- I
5 Hello World Example of JavaScript- II
6 Example of Clicking on a Form - I
7 Example of Clicking on a Form - II
8 Example of Parameterized HTML
9 The JavaScript Language -- Values, Names Etc.
10 The JavaScript Language -- Expressions - I
11 The JavaScript Language -- Expressions - II
12 The JavaScript Language -- Conditionals
13 JavaScript Object Model -- I
14 JavaScript Object Model -- II
15 Example of a JavaScript Function
16 Creation of JavaScript Objects
17 Addition of Methods to Object Definitions
18 Final Version of Display "Constructor"
19 The JavaScript with Statement for objects
20 The for ... in JavaScript syntax
21 The MakeArray Function and Arrays of Objects - I
22 The MakeArray Function and Arrays of Objects - II
23 The arguments Array in JavaScript
24 The this keyword in JavaScript
25 The parseInt parseFloat System functions
26 The eval JavaScript Function
27 The Math Object in JavaScript
28 The string Object in JavaScript - I
29 Explanation of string methods - I
30 The string Object in JavaScript - II
31 Explanation of string methods - II
32 The Date Object in JavaScript
33 The Structure of the Navigator Object/Property Hierarchy
34 The Confused Window Labelling Scheme
35 Role of Frames in JavaScript
36 Frame Basics in Netscape HTML -- Example
37 Frame Basics in Netscape HTML -- Rules
38 Use of Dummy Frames in JavaScript
39 General Syntax of <Frameset> </Frameset>
40 General Syntax of <Frame> tag
41 Event Handlers in JavaScript - I
42 Event Handlers in JavaScript - II
43 Some JavaScript Examples -- I
44 Some JavaScript Examples -- II
45 Structure of Index -- mainframe Case
46 Self Documenting Index-mainframe sets
47 AccumulateInfo Self Describing Document
48 Typical Look of Document Calling AccumulateInfo - I
49 Typical Look of Document Calling AccumulateInfo - II
50 The Asynchronous JavaScript/Browser
51 Another Important Way of setting a new document to be loaded
52 Use of Dynamic Forms (Layout) in JavaScript
53 The flexbuttons dynamic form in JavaScript
54 Create RadioButtons Dynamically
55 Create Select Field Dynamically

This table of Contents Abstract



HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 1 CPS 616
January-April 1996
Computational Science Track on base technologies for the Information Age:
Module on JavaScript from Netscape

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
Instructor: Geoffrey Fox
Version 25 February 96
teamed with Wojtek Furmanski, Nancy McCracken
Syracuse University
111 College Place
Syracuse
New York 13244-4100

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 2 Abstract of CPS616 JavaScript Presentatation

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
Some Simple Motivating Examples
Language Features and Syntax
The Peculiar Object Model -- Functions Properties and Methods
MakeArray and how to fool Interpreter into Arrays
Arguments of Functions
with and other object related syntax
The Math String and Date Objects
The Navigator Objects
Event Handling
User Objects and examples including using JavaScript for frames

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 3 General Remarks on JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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
Now we can use it as an alternative to Java where the "rapid prototyping" of a fully scriped language is helpful
JavaScript can be thought of as Java with the AWT (Abstract Windowing Toolkit) replaced by Netscape Client
JavaScript particularly useful for multi-frame windows and for manipulating forms without complex CGI (Server Side) scripts

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 4 Hello World Example of JavaScript- I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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 26 February 1996

Foil 5 Hello World Example of JavaScript- II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 6 Example of Clicking on a Form - I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<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 26 February 1996

Foil 7 Example of Clicking on a Form - II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * 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 26 February 1996

Foil 8 Example of Parameterized HTML

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * Critical Information in IMAGE
Full HTML Index
<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 26 February 1996

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

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 10 The JavaScript Language -- Expressions - I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 11 The JavaScript Language -- Expressions - II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 12 The JavaScript Language -- Conditionals

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 13 JavaScript Object Model -- I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 14 JavaScript Object Model -- II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 15 Example of a JavaScript Function

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 16 Creation of JavaScript Objects

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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
function Display(no) {
this.displayno = no; // Label display instance
this.pageframe = 'foil'; // Default for name of frame to put page in
this.indexframe= 'list'; // Default for name of frame to be index in
this.pagepointer = null; // Default URL for page to use
this.indexpointer = null; // Default URL for index to use
}
cps616 = new Display(1); // create an object cps616
cps616.pagepointer = "../cps616over96/webfoilindex.html";
cps616.indexpointer = "../cps616over96/foillist.html";

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 17 Addition of Methods to Object Definitions

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
Define a new function outside Display by
function LoadDisplay {
top.setframe(this.pagepointer,this.pageframe);
top.setframe(this.indexpointer,this.indexframe);
}
Add to Display definition after this.indexpointer = null;
this.LoadDisplay = LoadDisplay;
Now executing cps616.LoadDisplay(); // should load pages of CPS616 into their specified frames
General Syntax is:
Objectname.methodname = functionname;
where Objectname is an existing Object

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 18 Final Version of Display "Constructor"

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
This leads to "final" version of Display
function Display(no) {
this.displayno = no; // Label display instance
this.pageframe = 'foil'; // Default for name of frame to put page in
this.indexframe= 'list'; // Default for name of frame to be index in
this.pagepointer = null; // Default URL for page to use
this.indexpointer = null; // Default URL for index to use
this.LoadDisplay = LoadDisplay; // call this method to load URL's into pages
}

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 19 The JavaScript with Statement for objects

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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 26 February 1996

Foil 20 The for ... in JavaScript syntax

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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 26 February 1996

Foil 21 The MakeArray Function and Arrays of Objects - I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
Somewhat peculiarly, one can refer to properties of any object in an array notation. Namely:
cps616[0]; is same as cps616.displayno;
cps616[4]; is same as cps616.indexpointer;
This feature can be used to define objects that act just like arrays: set magic function
function MakeArray(size) {
this.length = size;
for( var i=1; i<=size; i++ ) {
this[i]= 0; }
}

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 22 The MakeArray Function and Arrays of Objects - II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
var maxdisplay = 10;
displays = new MakeArray(maxdisplay);
for( var n=1; n <= maxdisplay; n++) {
displays[n] = new Display(n); } // set elements of displays to be objects of "class" Display
Now we have an array of Display objects of length maxdisplay which can be referenced as displays[1] ... displays[maxdisplay] with properties such as
displays[currentdisplay].pageframe; etc.
This can be nested with MakeArray used say inside a function such as Display to get variables referenced like
displays[currentdisplay].nestedarray[itsindex]; // and so on for more array indices -- this implies we put in Display
this.nestedindex = new MakeArray (whathaveyou) ;
for( var n=1; n <= whathaveyou; n++) {
nestedindex[n] = null; } // Override initialization in MakeArray

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 23 The arguments Array in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 24 The this keyword in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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 26 February 1996

Foil 25 The parseInt parseFloat System functions

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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 26 February 1996

Foil 26 The eval JavaScript Function

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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")

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 27 The Math Object in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
There are currently four built in types of objects in JavaScript
  • Date, Math , string (one object each -- string is lower case s) plus a whole bunch connected with HTML documents
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

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 28 The string Object in JavaScript - I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 29 Explanation of string methods - I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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) and they start with a capital S!
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 26 February 1996

Foil 30 The string Object in JavaScript - II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
/* 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 26 February 1996

Foil 31 Explanation of string methods - II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 32 The Date Object in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 33 The Structure of the Navigator Object/Property Hierarchy

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * Critical Information in IMAGE
Full HTML Index
This is still unclear as documentation incomplete and what works changes with time!

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 34 The Confused Window Labelling Scheme

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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
Note manual written to accomodate both client(navigator) and server(LiveWire) objects but this presentation only covers client side (Server side introduced April 96)
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 are array properties
top parent self are properties labelling particular frames and windows

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 35 Role of Frames in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 26 February 1996

Foil 36 Frame Basics in Netscape HTML -- Example

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * Critical Information in IMAGE
Full HTML Index
<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 26 February 1996

Foil 37 Frame Basics in Netscape HTML -- Rules

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
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 <FRAMES>'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 26 February 1996

Foil 38 Use of Dummy Frames in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<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 26 February 1996

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

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<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 26 February 1996

Foil 40 General Syntax of <Frame> tag

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<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 26 February 1996

Foil 41 Event Handlers in JavaScript - I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
There are three major types of events which you can add event handlers
  • Form related events
  • links
  • Loading and Unloading new window
These are new attributes inside tags which traditionally respond to Mouse clicks or movement (or possibly text input)
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 ... >

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 42 Event Handlers in JavaScript - II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
onClick -- button,checkbox,radio,reset,submit in forms
    • -- links specified by <a > -- handler called when item clicked
onFocus -- select,text,textarea in forms -- handler called when Mouse lies in scope of this field
onBlur is opposite of onFocus and corresponds to Mouse leaving scope of those form fields
onChange -- select,text,textarea in forms when change occurs in these fields
onMouseOver -- plays same role for link that onFocus does for form elements
onSelect -- text or textarea in forms -- handler called when text selected
onSubmit -- forms -- handler called when submit button on form clicked

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 43 Some JavaScript Examples -- I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<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 26 February 1996

Foil 44 Some JavaScript Examples -- II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<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.
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(name,file) {
name.target="top.mainframe";
name.href = checkurl("http://www.npac.syr.edu/wisdom/",file); }

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 45 Structure of Index -- mainframe Case

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * Critical Information in IMAGE
Full HTML Index
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 26 February 1996

Foil 46 Self Documenting Index-mainframe sets

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
An Interesting use of JavaScript is produce documents that carry with them the necessary information to be used in a Index -- manframe example system
The idea is that pages loaded into subsidiary frames carry with them the necessary JavaScript to set appropriate control structures in top (the HTML page defining frames)
For instance there could be FIRST NEXT CAROUSEL PREVIOUS etc. options in top to loop through URL's of a given set
These can be neatly preset by a call to a routine such as AccumulateInfo on following foil
Options specify name (worldname) or need for special processing (style)
Other options specify URL's of related documents -- indices/Foils to loop through etc.
Note all calls are optional

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 47 AccumulateInfo Self Describing Document

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
function AccumulateInfo(option,value) {
if( option == 'processit!' )
  • top.ProcessDataLoaded();
if( option == 'style' ) {
indexstyle = value + ""; /* As JavaScript Bug */
return; }
if( option == 'worldname' ) {
newworldname = value + "";
return; }
......................
ErrorMessage("Illegal Option","AccumulateInfo",option);
return;
} // End AccumulateInfo

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 48 Typical Look of Document Calling AccumulateInfo - I

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<script language="JavaScript">
<!--scriptbegin
top.textsize('title',72);
top.textsize('bullet1',42,47,81);
top.textsize('reset');
top.AccumulateInfoPage('familyname',"CPS616");
top.AccumulateInfoPage('worldname',"NPAC");
top.AccumulateInfoPage('style','webfoil');
//scriptend-->
</script>
</head>

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 49 Typical Look of Document Calling AccumulateInfo - II

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
<body>
<script language="JavaScript">
<!--scriptbegin
document.writeln('<body bgcolor=' + top.currentparameters.bgcolor + ' text=' + top.currentparameters.fgcolor + ' link=' +top.currentparameters.linkcolor + ' vlink=' + top.currentparameters.vlinkcolor + ' alink=' + top.currentparameters.alinkcolor + '>');
document.writeln('<basefont size=' + top.currentparameters.fontsize + '>');
document.writeln('<font size=' + top.currentparameters.fontsize + ' color=' + top.currentparameters.titlecolor + '>');
top.foilsettitle('This is a Test Page');
document.writeln('</font>');
top.AccumulateInfoPage('processit!'); // Essential

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 50 The Asynchronous JavaScript/Browser

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color 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"
In self-documenting pages: one
  • First requests page to be loaded (say from top frame) by setting location property for frame.
  • The Javascript code in top continues without waiting for page to be loaded
  • Thus you need to know when information has been loaded -- this is purpose of top.AccumulateInfoPage('processit!'); call

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 51 Another Important Way of setting a new document to be loaded

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
localframe = displays[currentdisplay].pageframe; // List of labels of frames in frameset
if( (localframe != 'main') && (localframe != 'top') )
top.frames[localframe].location.href = pages[pageused].pageurl;
else top.location = pages[pageused].pageurl;
This code snippet shows an example where an array pages[pageused] (actually a structure with various information) stored in top hold URL's and we directly set location property of frame
location is object holding URL of page in object
location and location.href can be used interchangeably

HELP! * GREY=local HTML version of LOCAL Foils prepared 26 February 1996

Foil 52 Use of Dynamic Forms (Layout) in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * 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 26 February 1996

Foil 53 The flexbuttons dynamic form in JavaScript

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * 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 26 February 1996

Foil 54 Create RadioButtons Dynamically

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * 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 26 February 1996

Foil 55 Create Select Field Dynamically

From CPS616 Lectures on JavaScript CPS616 Basic Information Track for Computational Science -- Winter-Spring Semester 96. * See also color IMAGE
Full HTML Index
else { // Case whem 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 Tue Feb 18 1997