Given by Geoffrey Fox at CPS616 spring 1997 on Feb 17 and 19 1997. Foils prepared 21 February 97
Abstract * Foil Index for this file
Secs 76.3
See also color IMAGE
Basic Language variables and Statements |
Objects, functions and constructors |
New and Old Array syntax |
Built in Objects and Methods including parseInt, parseFloat, eval, Date, String, Math, Function and Number |
Frames in HTML and JavaScript |
Event Handlers |
setTimeout / clearTimeout |
This table of Contents
Abstract
Instructor: Nancy McCracken |
teamed with Meryem Ispirli, Geoffrey Fox, |
Tom Scavo, John Yip |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
Basic Language variables and Statements |
Objects, functions and constructors |
New and Old Array syntax |
Built in Objects and Methods including parseInt, parseFloat, eval, Date, String, Math, Function and Number |
Frames in HTML and JavaScript |
Event Handlers |
setTimeout / clearTimeout |
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 |
See Original Foil |
JavaScript expressions and basic operators are similar to C PERL and Java |
Assignment Operators are = += -= *= /= %= <<= >>= >>>= &= ^= |=
|
Conditional Expressions
|
Arithmetic operators are as usual with in addition ++ and --
|
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
|
x= "Hello "; y= "World!"; |
x + y is "Hello World!" |
See Original Foil |
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 |
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. |
See Original Foil |
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
|
top.setframe("help.html","maindisplay"); |
function setframe(relativeurldesired,framelabel) {
|
} |
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 |
See Original Foil |
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 |
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! |
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 |
} |
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")); |
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 |
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! |
Note one can easily define and use multidimensional arrays as in syntax
|
Arrays (the new ones!) have some interesting methods
|
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 |
See Original Foil |
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! |
this keyword can be very important but it is also confusing as not clear what it refers to at times.
|
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 |
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
|
on platforms that support it, parseInt and parseFloat will return NaN (Not a Number) when argument is inappropriate |
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 |
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
|
We have described Array and will ignore Boolean |
We will review the others in following |
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
|
We have described Array and will ignore Boolean |
We will review the others in following |
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:
|
See Original Foil |
See Original Foil |
See Original Foil |
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) {
|
} |
function seturl(name) { |
name.href = checkurl("http://www.npac.syr.edu/users/gcf/wisdom/","List.html"); |
} |
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 |
See Original Foil |
See Original Foil |
See Original Foil |
/* 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; } |
} |
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 |
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! |
See Original Foil |
See Original Foil |
Note window is basic concept and frames are children of window of same object type |
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
|
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 |
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 |
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
|
Javascript in spawned window can access properties of originating window as top.opener |
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.
|
<HTML> |
<HEAD> |
Bunch of JavaScript |
</HEAD> |
<FRAMESET ROWS="10%,80%,10%" > |
<FRAME SRC="topbanner.html" > |
<FRAMESET COLS="30%,70%" >
|
</FRAMESET> |
<FRAME SRC="bottombanner.html" > |
</FRAMESET> |
<NOFRAMES> |
<h2> This Page needs frames -- please find a kinder URL</b> |
</NOFRAMES> |
See Original Foil |
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 |
<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 |
<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
|
<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 |
There are four major types of events which you can add event handlers
|
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 |
See Original Foil |
See Original Foil |
You can set event handlers within HTML TAG using syntax like
|
Alternatively set event handler explicitly with
|
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
|
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) |
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 |
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
|
Note like eval, functionBody can be JavaScript constructed dynamically as in
|
<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 |
<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
|
function seturl(linkname,fileurl) { |
linkname.target="top.mainframe"; |
linkname.href = fileurl); } |
Top document has JavaScript in <head> </head> and defines <frameset></frameset> split in two by columns |
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
|
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 |
See Original Foil |
See Original Foil |
See Original Foil |
<SCRIPT> |
var timerID = null; // will be returned by call to setTimeout |
var timerrunning = false; |
function stopclock() { // terminate timeout
|
function startclock() |
{ // terminate timeout, display time, start timeout
|
function showtime() |
{ // display time, start timeout
|
</SCRIPT> |
The previous JavaScript goes in header of document whose body is: |
<BODY onLoad="startclock()" > |
<FORM name="clock" onSubmit="0" >
|
</FORM> |
</BODY> |
Note <FORM> only used for output using
|
onload function called when page is loaded and this starts timer. |