1 introduction to javascript presented by dr. joaquin vila developed by dr. billy b. l. lim &...

157
1 Introduction to JavaScript Presented by Dr. Joaquin Vila Developed by Dr. Billy B. L. Lim & Dr. Joaquin Vila Applied Computer Science Illinois State University From the InfoTech Internet/Intranet Series

Upload: piers-jones

Post on 27-Dec-2015

223 views

Category:

Documents


4 download

TRANSCRIPT

1

Introduction to JavaScript

Presented by

Dr. Joaquin Vila

Developed by

Dr. Billy B. L. Lim & Dr. Joaquin VilaApplied Computer Science

Illinois State University

From the InfoTech Internet/Intranet Series

2

Objectives

The objectives are to– provide participants with a solid introduction to

JavaScript, from the common to the exceptional– explore the language features of JavaScript– examine the various applications of JavaScript– discuss Java and JavaScript and contrast their

place in the World Wide Web

3

Agenda

Introduction Basic Language Features

– variables, expressions, operators, statements

The JavaScript Object Model – objects, properties, methods, events

Built-in Objects and Functions Examples and Miscellany

4

What is JavaScript? (Formerly LiveScript) Sun's simple, cross-

platform, WWW scripting language adopted by Netscape and allies.

Compact, user-level, object-based Ideal for making web pages “smart” Brief history

– developed primarily by Netscape, but in cooperation with Sun Microsystems Brendan Eich (Netscape) Bill Joy (Sun Microsystems)

5

Why JavaScript?

Java and JavaScript becoming defacto standards

Huge leap from static HTML coding to Java programming

Scripting makes things easy No additional tools needed

– (a browser and text editor will do!)

6

Server Based Processing

User’s InputServer

Processing

Client (browser) Server

7

Client Based Processing

User’s Input Server Processing

Client (browser) Server

JavaScriptProcessing

8

Uses of JavaScript

Tailor pages for the user Make interactive pages Process forms Provide CAI (computer-aided instructions) Special effects

9

JavaScript and Navigator versions

Navigator version Default JavaScript version <SCRIPT> tags supported

Navigator earlier than 2.0 JavaScript not supported None

Navigator 2.0 JavaScript 1.0 <SCRIPT LANGUAGE="JavaScript">

Navigator 3.0 JavaScript 1.1 <SCRIPT LANGUAGE = "JavaScript1.1">

and all earlier versions

Navigator 4.0-4.05 JavaScript 1.2 <SCRIPT LANGUAGE = "JavaScript1.2">

and all earlier versions

Navigator 4.06-4.5 JavaScript 1.3 <SCRIPT LANGUAGE = "JavaScript1.3">

… and all earlier versions

Navigator 6.0 JavaScript 1.5 <SCRIPT LANGUAGE = "JavaScript1.5">

and all earlier versions

10

Using JavaScript in HTML

JavaScript can be embedded in a HTML document in three ways: – 1. As statements and functions using the

SCRIPT tag. – 2. As event handlers using HTML tags. – 3. In javascript: <some javascript code here>

11

Your First JavaScript ProgramFileName: hello.htm

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

// This is a comment in JavaScript

document.write("<h1>Hello folks!</h1>");

</SCRIPT>

</HEAD>

<BODY>

Welcome to this class!

</BODY>

</HTML>

12

First Program (cont’d) <SCRIPT> and </SCRIPT> tags must surround

your JavaScript code

<SCRIPT LANGUAGE="JavaScript">

document.write("<h1>Hello folks!</h1>");

</SCRIPT>

Safest to put the tags within the <HEAD> LANGUAGE attribute is optional

Exercise 1

13

write Method

document.write directs the document object to write the given string

Examples:<script>counter = 10;document.write("<h1>Counter is "+counter+"</h1>"); </script>

<script>document.write("<IMG SRC=‘small.gif’>"); // notice the use of “ and ‘

</script>

Concatenate the strings and numbertogether and write the resultingstring out

14

Hiding JavaScript Code (from old browsers)

<SCRIPT>

<!-- Begin to hide script contents from old browsers.

Place JavaScript code here

// End the hiding here. -->

</SCRIPT>

15

NOSCRIPT Tag Use the <NOSCRIPT> tag to specify alternate content for browsers that do not

support JavaScript. HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not

support JavaScript; code within the tag is ignored by Navigator. Note however, that if the user has disabled JavaScript from the Advanced tab of the Preferences dialog, Navigator displays the code within the <NOSCRIPT> tag.

The following example shows a <NOSCRIPT> tag.

<NOSCRIPT><B>This page uses JavaScript, so you need to get Netscape Navigator 2.0or later!<BR><A HREF="http://home.netscape.com/comprod/mirror/index.html"><IMG SRC="NSNow.gif"></A>If you are using Navigator 2.0 or later, and you see this message,you should enable JavaScript by on the Advanced page of the Preferences dialog box.</NOSCRIPT>...

Exercise 2

16

Simple Interactions alert

– Displays an Alert dialog box with a message and an OK button.

– Syntax: alert("message");

– Example: alert(“You’re in a Special Area …”);

alert(“count=“+count); // count is a variable to be traced here

confirm– Displays a Confirm dialog box with the specified message and OK

and Cancel buttons.

– Syntax: confirm("message");

– Example: ans = confirm(“Are you sure you want to continue?”); ans will be true if OK is clicked or false if Cancel is clicked

17

Simple Interactions (2) eval

– The eval function evaluates a string and returns a value. – Syntax: eval(stringExpression)– Example: eval(1+2*3) // gives 7 here

prompt– The prompt function prompts for a string value. – Syntax: prompt(“message”) or prompt(“message”, default value)– Example:

aString1 = prompt(“Enter Name”); aString2 = prompt(“Enter Salary”, 0);

– Note: The return value is a string. Need to convert if a numeric value is desired. Use parseInt() or parseFloat().

– Example: numSalary = parseInt(aString2); numSalary = numSalary + 500;

18

Using javascript: (on the location field) Can test the simple interactions discussed above with the command to invoke the

JavaScript interpreter – javascript: on the location field of your browser (see figure below).

Exercise 3, 4

19

JavaScript vs. C/C++ Similarities

– comments /* */ and //– if, for, while, return– operators (arithmetic, relational, etc.)

Differences– In JavaScript

loose typing no file I/O library no pointers built-in string object

20

Data Types

Numbers– 1, 3.14159, -99

Logical (Boolean) values– true or false

Strings– “hello”, ‘hello’

null– special keyword denoting null value

21

String Literals A string literal is zero or more characters enclosed in double (")

or single (') quotes. A string must be delimited by quotes of the same type; that is, either both single quotes or double quotes. The following are examples of string literals:

– "Hello" – 'Hello' – "1234" – “one line \n another line”– '"Don\'t try that again!," I yelled.'

22

Variables

You use variables to hold values in your application.– Syntax:

var myVar; // var => local variable; Otherwise, the variable is global

JavaScript is a loosely typed language.myVar = 33;

myVar = “Hello World”;

myVar = 33 + “Hello World”; // gets “33Hello World”

myVar = “Hello World” + 33; // gets “Hello World33 ”

23

Variables

More Syntax– var Variablename = value;

var x = 3; var name = “ISU”; var x, y = 0; var x = null;

– Note: Null is: 0 (number), false (Boolean)

– There is no way to specify that a particular variable represents an integer, a string or a floating-point (real) number.

24

Variable Names A JavaScript identifier or name must start with a letter or

underscore ("_"); subsequent characters can also be digits (0-9). Letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). JavaScript is case-sensitive.

Some examples of legal names are:

– Last_Name

– status

– _name

25

Operators

Arithmetic + (Addition, String Concatenation)- (Subtraction, Unary Negation)* (Multiplication)/ (Division)% (Modulus) (e.g., 7 % 3 gives 1)

++ (Preincrement, Postincrement) // increments a variable by 1

e.g., x = 1; alert(x++); alert (x) // displays 1, then 2e.g., x = 1; alert(++x); alert (x) // displays 2, then 2

-- (Predecrement, Postdecrement) // decrements a variable by 1

e.g., x = 1; alert(x--); alert (x) // displays 1, then 0e.g., x = 1; alert(--x); alert (x) // displays 0, then 0

26

Operators (Cont...)

Assignment Operators = means assignment

PI = 3.14159; // var PI is assigned 3.14159

Op= (where op is one of +, -, *, /, etc.)x += y means x = x + y

x *= y means x = x * y

x -= y means x = x - y

x /= y means x = x / y

27

Operators (Cont...)

Relational Operators==, != (Equality, Inequality)

<, <=, =>, > (Arithmetic and String Comparison)

! (Logical Not)

&&, || (Logical AND, Logical OR)

?: (Conditional Selection)e.g., x = (1 < 5)? ‘a’:’b’; // here, x gets ‘a’

28

Operator Precedence The precedence of operators determines the order they are applied when

evaluating an expression. You can override operator precedence by using parentheses.

The precedence of operators, from lowest to highest is as follows: (Partial Listing)

– assignment = += -= *= /= %= – conditional ?: – logical-or || – logical-and && – equality == != – relational < <= > >= – addition/subtraction + - – multiply/divide * / % – negation/increment ! ++ -- – call, member () [] .

29

Expressions

An expression is any valid set of literals, variables, and operators that evaluates to a single value.PI = 3.14159

12 + 6

2 * PI * r

x++

x -= 3

30

Statements

Variable Declaration / Assignment Function Definition Conditionals Loops

– for loop– while loop– for...in loop– break and continue statements

with statement Comments

31

Comments

// Single Line var x // this part of the line is a comment /* Multiline Comment

Line 2.....

Line 3 */

32

Conditionals Syntax

if (condition) { statements

} [else { // else is not required else statements

}] Examples

if ( status == 1) { deduction = 500; marriedCount ++;

} else { singleCount ++;

deduction = 100;}

Exercise 5

33

Loops

Syntaxfor ([initial expression]; [condition]; [update expression]) {

statements}

Examplefor (var i = 0; i < 10; i++) {

document.write(i);}

See additional Example

Output:???

Exercise 8, 9

34

Loops (Cont...) Syntax

for (var in obj) {

statements }

ExamplesFileName: Winloop.htm<SCRIPT>// The following script shows all of the properties of the window object.for (var i in window) document.write (i + "<BR>");</SCRIPT>

FileName: Winloop2.htm<SCRIPT>// The following script shows all of the properties and their values of the window object.for (var i in window) document.write (i + "=" + window[i]+ "<BR>");</SCRIPT>

35

Loops (Cont...)

Syntax

while (condition) {

statements

} Example

n = 0;

x = 0;

while ( n < 3 ) {

n ++ ;

x += n;

}

Output:???

36

Loops (Cont...)

Syntax

continue Examples

i = 0;n = 0;while (i < 5) { i++; if (i == 2) continue; n += i;}document.write(n);

Output:13

37

Loops (Cont...) Syntax

break Examples

var i = 0;

while (i < 6) {

if (i == 3)

break;

i++;

document.write(i+”<BR>”);

}

Output:123

38

With Statement With, a statement that establishes object as the default object

for the statements. Syntax

with (object){ statements

} Examples

with (Math) { a = PI *r*r; x = r * cos(theta);

}

39

Functions Function

– A user-defined or built-in set of statements that perform a task. It can also return a value when used with the return statement.

– Syntax:

function name([param] [, param] [..., param]) { statements

} Example

// Takes an endValue and returns 1+2+3+ … + endValuefunction summation (endVal) { var thesum=0; for ( var iter = 1; iter <= endVal; iter++ ) thesum += iter; return ( thesum );}answer = summation(5);

Output:???

Exercise 6, 7

40

Arguments and ParametersFileName: argument.htm<HEAD><SCRIPT LANGUAGE="JavaScript"><!-- to hide script contents from old browsers function square(i) { document.write("The call passed “+ i + " to the function.“+"<BR>") return i * i } document.write("The function returned “+square(8)+".")// end hiding contents from old browsers --></SCRIPT></HEAD><BODY><BR>All done.</BODY>

41

A Simple FunctionFileName: firstFormEvent.htm<HEAD><SCRIPT LANGUAGE="JavaScript">function compute(form) { if (confirm("Are you sure?")) form.result.value = eval(form.expr.value) else alert("Please come back again.")}</SCRIPT></HEAD><BODY><FORM name=“MyForm”>Enter an expression:<INPUT TYPE="text" NAME="expr" SIZE=15 ><INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)"><BR>Result:<INPUT TYPE="text" NAME="result" SIZE=15 ><BR></FORM></BODY>

42

Another Function [Hall 98]

FileName: ShowInfo.html<HTML><HEAD> <TITLE>Extracting Doc Info</TITLE></HEAD>

<BODY BGCOLOR="WHITE"><H1>Extracting Document Info</H1><HR>

<SCRIPT LANGUAGE="JavaScript"><!--

function referringPage() { if (document.referrer.length == 0) return("<I>none</I>"); else return(document.referrer);}

document.writeln ("Document Info:\n" + "<UL>\n" + " <LI><B>URL:</B> " + document.location + "\n" + " <LI><B>Modification Date:</B> " + "\n" + document.lastModified + "\n" +" <LI><B>Title:</B> " + document.title + "\n" +" <LI><B>Referring page:</B> " + referringPage() + "\n" + "</UL>");

document.writeln ("Browser Info:" + "\n" + "<UL>" + "\n" + " <LI><B>Name:</B> " + navigator.appName + "\n" + " <LI><B>Version:</B> " + navigator.appVersion + "\n" + "</UL>");

// --></SCRIPT><HR> </BODY></HTML>

43

Arrays An array is an ordered set of values associated with

a single variable name.– Syntax:

arrayName = new Array()arrayName = new Array(arrayLength) // no enforcement of length

– To access the elements of an arrayarrayName[elementIndex]

– The first element of an array has an index of zero (0)

44

Arrays (Cont...)

Example: Each of these elements can be accessed by its index, as follows: – myCar[0] = "Ford"– myCar[1] = "Mustang"– myCar[2] = 67

Note: – Array elements can be heterogeneous (can

contain elements of multiple data types)

45

Arrays (Cont...) Properties and arrays in JavaScript are intimately

related; in fact, they are different interfaces to the same data structure.

Example:– you could set the properties of the myCar object described above as

follows: myCar["make"] = “Benz" myCar["model"] = “M Class 320" myCar["year"] = 99Or myCar.make = " Benz" myCar.model = " M Class 320" myCar.year = 99

46

Arrays (Cont...) Example:

FileName: Array.htm<script>anArray = new Array();anArray[0] = "aaa";anArray[2] = "ccc";anArray[9] = 99;anArray["myProperty"] = "someValue";anArray.myProperty2 = "someValue2";for (i = 0; i < anArray.length; i++)

document.write("anArray at "+i+" = "+anArray[i] +"<BR>");document.write("anArray at myProperty = " + anArray.myProperty +"<BR>");document.write("anArray at myProperty2 = " + anArray.myProperty2+"<BR>");</script>

47

JavaScript Object Model

Object-based (not object-oriented) scripting language– can manipulate instances of JavaScript’s built-in object types

e.g., date, document, location, etc.

– objects have properties (i.e., characteristics of objects) e.g., document.bgColor, ...

– objects have methods (i.e., services provided by the objects) e.g., document.write(“Hello”), ...

Can also create and use your own objects– later on this ...

48

JavaScript Objects

Both the object name and property name are case sensitive. You define a property by assigning it a value.– myCar.make = "Ford"– myCar.model = "Mustang"– myCar.year = 69

49

Objects and Properties Objects in Navigator exist in a hierarchy that reflects the hierarchical structure of the

HTML page itself

HTML Page in a Window Corresponding JavaScript Objects

window (= the window instance)document (= the page)links (= array with all the links in the page)images (= array with all the images)etc.

50

Objects and Properties (2)

An object's "descendants" are properties of the object– e.g., a form named "form1" is an object, but is also a property of document, and is

referred to as "document.form1"

ParentObject

ChildObject

Property of parent object

Property of child object

Property only

an object and a property

51

Object Hierarchy

52

Objects in a Page Every page has the following objects:

– navigator: has properties for the name and version of the Navigator being used, for the MIME types supported by the client, and for the plug-ins installed on the client.

– window: the top-level object; has properties that apply to the entire window. There is also a window object for each "child window" in a frames document.

– document: contains properties based on the content of the document, such as title, background color, links, and forms.

– location: has properties based on the current URL.

– history: contains properties representing URLs the client has previously requested.

Depending on its content, the document may contain other objects.

– For instance, each form (defined by a FORM tag) in the document has a corresponding Form object.

53

Featured Objects

(in alphabetical order)

54

Anchor Object (Anchors Array) A piece of text that can be the target of a hypertext

link. – If an anchor object is also a link object, the object has entries

in both the anchors and links arrays. – Example: Define an anchor for the text "Welcome to

JavaScript". <A NAME="javascript_intro"><H2>Welcome to

JavaScript</H2></A>– Example: If the preceding anchor is in a file called intro.htm,

a link in another file could define a jump to the anchor as follows: <A HREF="intro.html#javascript_intro">Introduction</A>

55

Button Object A pushbutton on an HTML form. Cannot be customized (can only change its length) Properties

– name reflects the NAME attribute – value reflects the VALUE attribute

Methods– click

Event handlers– onClick

56

Button Object (2)

To use a button object's properties and methods: – 1. buttonName.propertyName– 2. buttonName.methodName(parameters)– 3. formName.elements[index].propertyName– 4. formName.elements[index].methodName(parameters)

Example:– Create a button named calcButton. The text "Calculate" is displayed on the

face of the button. When the button is clicked, the function calcFunction() is called.

<INPUT TYPE="button" VALUE="Calculate" NAME="calcButton" onClick="calcFunction(this.form)">

57

Checkbox Object

A checkbox on an HTML form A toggle switch that lets the user set a value on or

off Properties

– checked lets you programatically check a checkbox – defaultChecked reflects the CHECKED attribute – name reflects the NAME attribute – value reflects the VALUE attribute

58

Checkbox Object (2) Methods: click Event handlers: onClick Property of: form Example:

The following example displays a group of four checkboxes that all appear checked by default.

– <B>Specify your music preferences (check all that apply):</B>– <BR><INPUT TYPE="checkbox" NAME="musicpref_rnb" CHECKED> R&B– <BR><INPUT TYPE="checkbox" NAME="musicpref_jazz" CHECKED> Jazz– <BR><INPUT TYPE="checkbox" NAME="musicpref_blues" CHECKED> Blues– <BR><INPUT TYPE="checkbox" NAME="musicpref_newage" CHECKED> New Age

59

Checkbox Object (3) Example:

FileName: toUpper.htm<SCRIPT>function convertField(field) { if (document.form1.convertUpper.checked) { field.value = field.value.toUpperCase()}}function convertAllFields() { document.form1.lastName.value = document.form1.lastName.value.toUpperCase() document.form1.firstName.value = document.form1.firstName.value.toUpperCase()}</SCRIPT><FORM NAME="form1"><B>Last name:</B><INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)"><BR><B>First name:</B><INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)"><P><INPUT TYPE="checkBox" NAME="convertUpper" onClick="if (this.checked) {convertAllFields()}"> Convert fields to upper case</FORM>

60

Date Object

Gets and sets the dates and times. A top-level built-in object Two (of many) ways to create a Date object:

– dateObjectName = new Date()

– dateObjectName = new Date(year, month, day, hours, minutes, seconds)

Properties– None.

61

Date Object (2)

Methods (partial list)– getDate, getDay, getHours, getMinutes, getMonth, getSeconds,

getTime, getYear, parse, setDate, setHours, setMinutes, setMonth, setSeconds, setTime, setYear, toGMTString, toLocaleString, UTC

Event handlers– None. Built-in objects do not have event handlers.

Property of– None.

62

Date Object (3)

Examples– now = new Date()– birthday = new Date("December 17, 1995

03:24:00")– birthday = new Date(95,11,17) // month’s range: 0 - 11

– birthday = new Date(95,11,17,3,24,0)– currentYear = birthday.getYear()

63

Date Object (4)

Examples<script>now = new Date();document.write("Time: "+now.getHours()+":"+now.getMinutes()+"<br>");document.write("Date: ” + (now.getMonth()+1) + "/” + now.getDate() + "/” +

(1900+now.getYear()));</script>

outputTime: 9:48

Date: 6/16/1999

Can also use getFullYear()– This gives a 4-digit year

64

Document Object

Contains information on the current document (e.g., title, last modified, color), and provides methods for displaying HTML output to the user.

To use a document object's properties and methods: – 1. document.propertyName

– 2. document.methodName(parameters)

65

Document Object (2)

Properties– alinkColor reflects the ALINK attribute – anchors is an array reflecting all the anchors in a document – bgColor reflects the BGCOLOR attribute – cookie specifies a cookie – fgColor reflects the TEXT attribute – forms is an array reflecting all the forms in a document – lastModified reflects the date a document was last modified – linkColor reflects the LINK attribute – links is an array reflecting all the links in a document – location reflects the complete URL of a document – referrer reflects the URL of the calling document – title reflects the contents of the <TITLE> tag – vlinkColor reflects the VLINK attribute

66

Document Object (3) Methods

– clear, close, open, write, writeln Event handlers

– None. The onLoad and onUnload event handlers are specified in the <BODY> tag but are actually event handlers for the window object.

Property of– Window (or Frame) object

Examples:– document.fgColor = "#ff0000"– document.form1.controlname = ...

67

Elements Array

An array of objects corresponding to form elements (such as checkbox, radio, and text objects) in source order.

Properties– length reflects the number of elements on a form

Property of– form

68

Elements Array (2) Example:

– if a form has a text field and two checkboxes, these elements are reflected as

formName.elements[0] formName.elements[1] formName.elements[2]

– alternately, formName.Name1 formName.Name2 formName.Name3

Note: – each radio button in a radio object appears as a separate element in the

elements array. – Elements in the elements array are read-only. (e.g., the statement

formName.elements[0]="music" has no effect)

69

Form Object (Forms Array)

Lets users input text and make choices from form objects such as checkboxes, radio buttons, and selection lists.

Can also be used to post data to a server To use a form object's properties and methods:

– 1. formName.propertyName– 2. formName.methodName(parameters)– 3. forms[index].propertyName– 4. forms[index].methodName(parameters)

70

Form Object (Forms Array) (2) The forms array

– 2 ways of referencing forms by using the forms array by using the form names

– form array contains an entry for each form object (<FORM> tag) in a document in source order.

– e.g., if a document contains three forms, these forms are reflected as document.forms[0], document.forms[1], and document.forms[2].

– To use the forms array: 1. document.forms[index] 2. document.forms.length

71

Form Object (Forms Array) (3) Properties

– action reflects the ACTION attribute – elements is an array reflecting all the elements in a form – encoding reflects the ENCTYPE attribute – length reflects the number of elements on a form – method reflects the METHOD attribute – target reflects the TARGET attribute – length reflects the number of forms in a document (for forms array)

Methods: submit

Event handlers: onSubmit Property of: document

72

Frame Object (Frames Array)

Frames enable the display of multiple independently scrollable frames on a single screen, each with its own distinct URL.

Frames can point to different URLs as well as be targeted by other URLs - all within the same screen.

73

Frames (2)

Frames HTML Syntax:

<HTML>

<HEAD>

</HEAD>

<FRAMESET>

</FRAMESET>

</HTML>

The Frame definitions go between the frameset tags

74

Frames (3)

The arguments taken by frameset tag are– ROWS - is the row values for the frames embedded in that

frameset.– COLS - takes the column values for the frames in the frameset– the values can be numbers or percentages

Example

<frameset cols="200,200">

</frameset>

<frameset rows="30%,70%>

</frameset>

75

Frames (4)

Inside framesets the only permitted tags are other framesets, frames and noframes.

Frame tag defines the actual frames. It takes arguments like SRC, MarginWidth, Scrolling etc.

noframes tag provide alternate content for browsers not having frames capability

76

Frames (5)

Sample frame scripting

<html>

<frameset rows="50%,*">

<frame src="http://www.yahoo.com">

<frame src="http://www.ilstu.edu">

</frameset>

77

Frames (6)

Frames with name tag:

<title>WebQuiz using JavaScript</title>

<frameset cols=60%,*>

<frame src="webQuiz.htm" name="main">

<frame src="webAnsw.htm" name="hello">

</frameset>

78

Frames (7)

Hypertext reference with a “Target” tag.

<h3>Correct Answers</h3>

<A href="webAnsw.htm#a1" Target="hello">#1</a>

79

Frames (8)

<HTML>

<HEAD>

<TITLE>HTML Analysis</TITLE>

</HEAD>

<FRAMESET ROWS="150,300,*">

<FRAME SRC="hanalysis1.htm" NAME="control">

<FRAME SRC="empty.htm" NAME="displayhere">

<FRAME SRC="empty.htm" NAME="analysis">

</FRAMESET>

</HTML>

80

Hidden Object

A text object that is suppressed from form display on an HTML form. A hidden object is used for passing name/value pairs when a form submits.

Typically used with CGI scripts to pass special data between the browser and the server

Value is reset when the document is reloaded (unlike other form elements)

81

Hidden Object (2)

Properties– name reflects the NAME attribute – value reflects the current value of the hidden object

Methods– None.

Event handlers– None.

Property of– form

82

Hidden Object (3)

Example:// uses a hidden object to store the value of the last object the user clicked

FileName: hidden.htm<FORM NAME="form1"><INPUT TYPE="hidden" NAME="hiddenObject" VALUE="None"><P><INPUT TYPE="button" VALUE="Click me" NAME="button1" onclick="document.form1.hiddenObject.value=this.value"><P><INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz" onClick="document.form1.hiddenObject.value=this.value"> Jazz<P><INPUT TYPE="button" VALUE="Display hidden value"

NAME="button2" onClick="alert('Last object clicked: ' + document.form1.hiddenObject.value)">

</FORM>

83

History Object Contains information on the URLs that the client has visited

within a window. Properties

– length reflects the number of entries in the history object Methods

– back, forward, go Event handlers

– None. Property of

– document

84

History Object (2) Examples:

– // goes to the URL the user visited three clicks ago in // the current windowhistory.go(-3)

– // causes window2 to go back one item in its window // (or session) history:window2.history.back()

85

Image Object / Images Array

Image array called document.images– created for all images defined by <IMG>– each is an Image object– use: document.images[0], document.images[1],

etc.– can dynamically change the content of graphics

document.images[0].src = “http://xyz.com/1.gif”;

86

Layers Created by the HTML <layer> or <ilayer> tag The JavaScript runtime engine creates a Layer object

corresponding to each layer in your document. It puts these objects in an array in the document.layer property. You access a Layer object by indexing this array.<html><layer name=pic z-index=0 left=200 top=100><img src="perry.jpg"></layer><layer name=txt z-index=1 left=200 top=400><font size=+2> <i> Layers-Demo: Perry </i> </font></layer></html>

87

Layers (2)

Property Descriptionname="layerName" The name of the layerleft=xPosition The horizontal position of the top left cornertop=yPosition The vertical position of the top left cornerz-index=layerIndex Index number of layerwidth=layerWidth Width of the layer in pixelclip="x1_offset,y1_offset,x2_offset,y2_offset" Defines the area of the layer which shall be

displayedabove="layerName" Defines above which layer this layer will

appearbelow="layerName" Defines below which layer this layer will

appearVisibility=show|hide|inherit The visibility of the layerbgcolor="rgbColor" The background color - either name of a

standard color or rgb-valuesbackground="imageURL" Background image

88

Layers (3)FileName: hideShow_Layers.htm<html><head><script language="JavaScript">function showHide() { if (document.layers["myLayer"].visibility == "show") document.layers["myLayer"].visibility= "hide" else document.layers["myLayer"].visibility= "show";}</script></head><body><ilayer name=myLayer visibility=show><font size=+1 color="#0000ff"><i>This text is inside a layer</i></font></ilayer><form><input type="button" value="Show/Hide layer" onClick="showHide()"></form></body></html>

89

Link Object (Links Array)

A piece of text or an image identified as a hypertext link. When the user clicks the link text, the link hypertext reference is loaded into its target window.

Each link object is a location object and has the same properties as a location object.

If a link object is also an anchor object, the object has entries in both the anchors and links arrays.

90

Link Object (Links Array) (2) Properties

– hash specifies an anchor name in the URL – host specifies the hostname:port portion of the URL – hostname specifies the host and domain name, or IP address, of a network

host – href specifies the entire URL – pathname specifies the url-path portion of the URL – port specifies the communications port that the server uses for

communications – protocol specifies the beginning of the URL, including the colon – search specifies a query – target reflects the TARGET attribute – length reflects the number of links in a document (for link array)

91

Link Object (Links Array) (3) Methods: None.

Event handlers: onClick, onMouseOver

Property of: document

Examples– // creates a hypertext link to an anchor named numbers in the file

DOC3.HTML in the window window2. If window2 does not exist, it is created.

– <A HREF=doc3.html#numbers TARGET="window2">Numbers</A>– // takes the user back x entries in the history list:

<A HREF="javascript:history.go(-1 * x)">Click here</A>

92

Location Object

Contains information on the current URL Use this object to set or get the URL of a window

or frame Properties

– same as the ones in link object Methods: None.

Event handlers: None.

Property of: document

93

Location Object (2)

Examples:– // sets the URL of the current window to the

Netscape home page: window.location.href=“http://home.netscape.com/”or simply window.location=“http://home.netscape.com/”

– // sets the URL of a frame named frame2 to the Sun home page: parent.frame2.location.href="http://www.sun.com/"

94

Navigator Object Use the navigator object to determine which version of

the Navigator your users have. Properties

– appCodeName specifies the code name of the browser – appName specifies the name of the browser – appVersion specifies version information for the Navigator – userAgent specifies the user-agent header

Methods: None. Event handlers: None. Property of: None. Example:

– alert(“This version of Netscape is “ + navigator.appVersion)

95

Password Object

A text field on an HTML form that conceals its value by displaying asterisks (*). When the user enters text into the field, asterisks (*) hide anything entered from view.

Properties– defaultValue reflects the VALUE attribute – name reflects the NAME attribute – value reflects the current value of the password object's field (If a

user interactively modifies the value in the password field, you cannot evaluate it for security reasons. )

96

Password Object (2)

Methods– focus – blur – select

Event handlers– None.

Property of– form

Examples– <B>Password:</B> <INPUT TYPE="password"

NAME="password" VALUE="" SIZE=25>

97

Plugin A Plugin object is a plug-in installed on the client.

– A plug-in is a software module that the browser can invoke to display specialized types of embedded data within the browser. The user can obtain a list of installed plug-ins by choosing About Plug-ins from the Help menu.

Each Plugin object is itself array containing one element for each MIME type supported by the plug-in. Each element of the array is a MimeType object.

– For example, the following code displays the type and description properties of the first Plugin object's first MimeType object.

myPlugin=navigator.plugins[0]myMimeType=myPlugin[0]document.writeln('myMimeType.type is ',myMimeType.type,"<BR>")document.writeln('myMimeType.description is ',myMimeType.description)

sample output: myMimeType.type is video/quicktimemyMimeType.description is QuickTime for Windows

98

Radio Object

A set of radio buttons on an HTML form, allowing the user choose one item from a list.

All radio buttons in a radio button group use the same name property.

To access the individual radio buttons, follow the object name with an index starting from zero

– document.forms[0].radioName[0] is the first, document.forms[0].radioName[1] is the second, etc.

99

Radio Object (2) Properties

– checked lets you programatically select a radio button – defaultChecked reflects the CHECKED attribute – length reflects the number of radio buttons in a radio object – name reflects the NAME attribute – value reflects the VALUE attribute

Methods: click

Event handlers: onClick

Property of: form

100

Radio Object (3) Examples

FileName: radio.htm<form name=musicForm><INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b" onClick="musicForm.catalog.value = 'soul-and-r&b'"> Soul and R&B<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz" onClick="musicForm.catalog.value = 'jazz'"> Jazz<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical" onClick="musicForm.catalog.value = 'classical'"> Classical<BR> Selected Music:<INPUT TYPE="text" NAME="catalog" SIZE="20"></form>

101

Radio Object (4)

Example:Submit form using a server program (a home-made Java servlet called EchoAll)

FileName: radio2.htm<form name=musicForm method="get" action="http://appsrv.acs.ilstu.edu/355/servlet/EchoAll">

<INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b" onClick="musicForm.catalog.value = 'soul-and-r&b'"> Soul<br>

<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz" onClick="musicForm.catalog.value = 'jazz'"> Jazz<br>

<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical" onClick="musicForm.catalog.value = 'classical'"> Classical<br>

<BR>

Selected Music: <INPUT TYPE="text" NAME="catalog" SIZE="20">

<input type="submit">

</form>

102

Select Object (Options Array)

A selection list or scrolling list on an HTML form. A selection list lets the user choose one item from a list. A scrolling list lets the user choose one or more items from a list.

Properties– The select object has the following properties:

length reflects the number of options in a select object name reflects the NAME attribute options reflects the <OPTION> tags selectedIndex reflects the index of the selected option (or the first

selected option, if multiple options are selected)

103

Select Object (Options Array) (2)

– The options array has the following properties: defaultSelected reflects the SELECTED attribute index reflects the index of an option length reflects the number of options in a select object name reflects the NAME attribute selected lets you programatically select an option selectedIndex reflects the index of the selected option text reflects the textToDisplay that follows an <OPTION> tag value reflects the VALUE attribute

104

Select Object (Options Array) (3) Methods

– blur – focus

Event handlers– onBlur – onChange – onFocus

Property of– The select object is a property of form – The options array is a property of select

105

Select Object (Options Array) (4) Example:

FileName: select.htm// Displays a selection list and a scrolling list. Then shows the selections.<SCRIPT>function testSelect(form) { index = form.music_type_single.selectedIndex alert(form.music_type_single.options[index].text+" and "+

form.music_type_multi.selectedIndex)}</SCRIPT><form>Choose the music type for your free CD:<SELECT NAME="music_type_single"> <OPTION SELECTED> R&B <OPTION> Jazz <OPTION> Blues</SELECT><P>Choose the music types for your free CDs:<BR><SELECT NAME="music_type_multi" MULTIPLE> <OPTION SELECTED> R&B <OPTION> Jazz <OPTION> Blues</SELECT><P><INPUT TYPE="BUTTON" NAME="Button" VALUE="ClickMe" onClick="testSelect(this.form)"></form>

106

String Object

A series of characters. Properties

– length reflects the length of the string Methods

– anchor, big, blink, bold, charAt, fixed, fontcolor, fontsize, indexOf, italics, lastIndexOf, link, small, strike, sub, substring, sup, toLowerCase, toUpperCase

Event handlers: None. Property of: None.

107

String Object (2)

Examples– The following statement creates a string variable.

var last_name = "Schaefer" last_name.length // gives 8 last_name.toUpperCase() // gives “SCHAEFER” last_name.toLowerCase() // gives “schaefer” last_name.indexOf(“e”) // gives 4 last_name.indexOf(“x”) // gives –1 (for not found) last_name.substring(2,5) // gives “hae” (1st index is inclusive, 2nd index

is exclusive) Last_name.substr(1,4) // gives “chae” (starting at 1, extract 4 chars)

108

Submit Object A submit button on an HTML form. A submit button

causes a form to be submitted. Example:

FileName: submit.htm

// With JavaScript, can get the user the confirm before submitting a form.

<SCRIPT>

function submitMe(form) {if (confirm(“Are you sure you want to submit this form?”))

return (true)else

return (false)}</SCRIPT><form onSubmit=“return submitMe(this)”><INPUT TYPE="TEXT" NAME="Box" VALUE=""><INPUT TYPE="submit"> </form>

true => form is submitted false => submit process is aborted

109

Text Object A text input field on an HTML form. A text field

lets the user enter a word, phrase, or series of numbers.

Text objects can be updated (redrawn) dynamically by setting the value property (this.value).

Properties– defaultValue reflects the VALUE attribute – name reflects the NAME attribute – value reflects the current value of the text object's field

110

Text Object (2) Methods

– focus – blur – select

Event handlers– onBlur – onChange – onFocus – onSelect

Property of– form

111

Text Object (3) Examples:

– FileName: text.htm// creates a text object that is 25 characters long. The text field appears immediately to the

right of the words "Last name:". The text field is blank when the form loads.

<B>Last name:</B> <INPUT TYPE="text" NAME="last_name" VALUE="" SIZE=25>

// creates two text objects on a form. Each object has a default value. The city object has an onFocus event handler that selects all the text in the field when the user tabs to that field. The state object has an onChange event handler that forces the value to upper case.

<FORM NAME="form1"><BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Anchorage" SIZE="20" onFocus="this.select()"><B>State: </B><INPUT TYPE="text" NAME="state" VALUE="AK" SIZE="2" onChange="this.value=this.value.toUpperCase()"></FORM>

112

Textarea Object

A multiline input field on an HTML form. A textarea field lets the user enter words, phrases, or numbers.

Properties– defaultValue reflects the VALUE attribute – name reflects the NAME attribute – value reflects the current value of the text object's field

Methods– focus, blur, select

113

Textarea Object (2)

Event handlers– onBlur

– onChange

– onFocus

– onSelect

Property of– form

114

Window Object

The top-level object for each document, location, and history object group.

To define a window, use the open method: – var myWin = window.open("URL", "windowName"

[,"windowFeatures"])

e.g.,

var myWin = window.open(“www.ilstu.edu", “Window1”,“height=300,width=400,toolbar=yes,scrollbar=yes")

No space!!!

115

Window Object (2) Properties

– defaultStatus reflects the default message displayed in the window's status bar – frames is an array reflecting all the frames in a window – length reflects the number of frames in a parent window – name reflects the windowName argument – parent is a synonym for the windowName argument and refers to a window

containing a frameset – self is a synonym for the windowName argument and refers to the current

window – status specifies a priority or transient message in the window's status bar – top is a synonym for the windowName argument and refers to the top-most

Navigator window – window is a synonym for the windowName argument and refers to the current

window

116

Window Object (3) Methods

– alert – close – confirm – open – prompt – setTimeout – clearTimeout

Event handlers– onLoad – onUnload

Property of– None.

117

Window Object (4) Example:

– In the following example, the document in the top window opens a second window, window2, and defines pushbuttons that open a message window, write to the message window, close the message window, and close window2. The onLoad and onUnload event handlers of the document loaded into window2 display alerts when the window opens and closes.

– WIN1.HTM, which defines the frames for the first window, contains the following code: <HTML><HEAD><TITLE>Window object example: Window 1</TITLE></HEAD><BODY BGCOLOR="antiquewhite"><SCRIPT>window2=open("win2.htm","secondWindow","scrollbars=yes,width=250, height=400")document.writeln("<B>The first window has no name: " + window.name + "</B>")document.writeln("<BR><B>The second window is named: " + window2.name + "</B>")</SCRIPT>

118

Window Object (5)<FORM NAME="form1">

<P><INPUT TYPE="button" VALUE="Open a message window"

onClick="window3=window.open('','messageWindow','scrollbars=yes,width=175, height=300')">

<P><INPUT TYPE="button" VALUE="Write to the message window"

onClick="window3.document.writeln('Hey there');window3.document.close()">

<P><INPUT TYPE="button" VALUE="Close the message window"

onClick="window3.close()">

<P><INPUT TYPE="button" VALUE="Close window2"

onClick="window2.close()">

</FORM>

</BODY>

</HTML>

119

Window Object (6)– WIN2.HTM, which defines the content for window2, contains the following code:

<HTML><HEAD><TITLE>Window object example: Window 2</TITLE></HEAD><BODY BGCOLOR="oldlace" onLoad="alert('Message from ' + window.name + ': Hello, World.')" onUnload="alert('Message from ' + window.name + ': I\'m closing')"><B>Some numbers</B><LI>one<LI>two<LI>three</BODY></HTML>

120

Event Handling

121

Event Handling JavaScript provides a moderate level of event

detection to pass control to functions attached to built-in event handlers

e.g.,– <INPUT type=“button” VALUE=“button1”– onClick=“computeSomething()”>

Events are triggered in the browser primarily by user actions such as button click, page load, form submit.

122

Event Handlers

The following event handlers are available in JavaScript: – onAbort – onBlur – onChange – onClick – onDragDrop – onError – onFocus – onKeyDown– onKeyPress – onKeyUp – onLoad

– onMouseDown– onMouseMove– onMouseOut – onMouseOver – onMouseUp– onMove– onReset– onResize– onSelect– onSubmit – onUnload

123

Event Handlers (Cont...) onAbort

– An abort event occurs when a user aborts the loading of an image (for example by clicking a link or clicking the Stop button)

onBlur – A blur event occurs when a select, text, or textarea field on a form

loses focus. onChange

– A change event occurs when a select, text, or textarea field loses focus and its value has been modified.

onClick– A click event occurs when an object on a form is clicked.

124

Event Handlers (Cont...) onDragDrop

– A drapDrop event occurs when a user drops an object onto the browser window, such as dropping a file on the browser window

onError – An error event occurs when the loading of a document or image

causes an error

onFocus– A focus event occurs when a field receives input focus by tabbing

with the keyboard or clicking with the mouse. onKeyDown, onKeyPress, onKeyUp

– A keyDown, keyPress, or keyUp event occurs when a user depresses a key, presses or holds down a key, or releases a key, respectively

125

Event Handlers (Cont...) onLoad

– A load event occurs when Navigator finishes loading a window or all frames within a <FRAMESET>.

– Examples In the following example, the onLoad event handler displays a

greeting message after a web page is loaded. <BODY onLoad="window.alert('Welcome to my home page!')">

onMouseDown, onMouseMove, onMouseOut, onMouseOver, and onMouseUp

– A MouseDown, MouseMove, MouseOut, MouseOver, or MouseUp event occurs when a user depresses a mouse button, moves a cursor, moves a cursor out of a link or image map, moves a cursor over a link, releases a mouse button, respectively

126

Event Handlers (Cont...)

onMouseOver– A mouseOver event occurs once each time the

mouse pointer moves over an object from outside that object.

Example<A HREF="http://www.ilstu.edu/"

onMouseOver="window.status=‘A Good Place …!'; return true">

Click me</A>Return true tells the browser not to perform its ownevent handling routine of displaying the link’s URLin the status bar

127

Event Handlers (Cont...) OnResize

– A Resize event occurs when a user or script resizes a window

<html><head><script language="JavaScript">window.onresize= message;function message() { alert("The window has been resized!");}</script></head><body>Please resize the window.</body></html>

128

Event Handlers (Cont...) Another look at onClick:

<body><form name="myForm"><input type="button" name="myButton" value="ClickMe!" ></form><script language="JavaScript">document.myForm.myButton.onClick= message;

function message() { alert('Click event occured!');}

</script></body>

129

Event Handlers (Cont...)

onSelect

– A select event occurs when a user selects some of the text within a text or textarea field.

onSubmit

– A submit event occurs when a user submits a form onUnload

– An unload event occurs when you exit a document.

130

Form ValidationFileName: valid2.htm<html><head><script language="JavaScript">function test1(form) { if (form.text1.value == "") alert("Please enter a string!") else { alert("Hi "+form.text1.value+"! Form input

ok!"); }}function test2(form) { if (form.text2.value == "" || form.text2.value.indexOf('@') == -1) alert("No valid e-mail address!"); else alert("OK!");}// --></script></head>

<body>

<form name="first">

Enter your name:<br>

<input type="text" name="text1">

<input type="button" name="button1" value="Test Input" onClick="test1(this.form)">

<P>

Enter your e-mail address:<br>

<input type="text" name="text2">

<input type="button" name="button2" value="Test Input" onClick="test2(this.form)">

</body>

131

Form Validation (2)FileName: Ex-valid.htm<HTML><HEAD><SCRIPT LANGUAGE="JavaScript">function checkit() { var strval = document.myform.mytext.value; var intval = parseInt(strval); if ( intval > 0 && intval < 10 ) { return(true); } else { alert("Input value " + strval + " is out of

range"); return(false); }}</SCRIPT></HEAD>

<BODY>

<P>

<HR><FORM NAME="myform" onSubmit="checkit()"></P>

<P>Enter a number between 1 and 9: <INPUT TYPE="text" NAME="mytext" VALUE="" SIZE="10"></P>

<P><BR>

<INPUT TYPE="submit"></FORM>

<HR></P>

</BODY>

</HTML>

132

Form Validation (3)

FileName: testNaN.htm// Shows NaN and the use of isNaN()<html><head><script language="JavaScript">

function test2(form) {var ans = parseInt(form.text2.value); if (isNaN(ans)) alert("NaN (Not A Number)!"); else alert("OK!");}

</script></head>

<body>

<form>

Enter a number:<br>

<input type="text" name="text2">

<input type="button" name="button2" value="Test Input" onclick="test2(this.form)">

</form>

</body>

</HTML>

This function returns true if the 1st digit can beparsed into a number. Otherwise, it returns false.

133

Sound

Playing sound while loading a page– insert location = soundURL at the head

<HEAD>

<SCRIPT>

location = “mySound.au”

</SCRIPT>

</HEAD>

– Netscape “spawns” the NAPLAYER application to play the sound file

134

Sound (2)

Playing sound after a page has loaded– insert location = soundURL in the onLoad

event

<BODY onLoad="location = ‘mySound.au'">

</BODY>

– Equivalently, upon onLoad call a function that contains the statement location = soundURL

135

Sound (3)

Playing sound in response to an event– use the <A> link anchor and link it to a sound

file

<BODY><A HREF = "mySound.au”>Click here to play a sound</A></BODY>

– Equivalently, upon onClick call a function that contains the statement location = soundURL

136

Animation “The best way to animate images using JavaScript

is not to.” JavaScript is no better than others that do not

require it– Can’t update “in-place,” has to update whole page

Typically need at least three frames– one frame controls the animation and another is for the output To

ensure steady inflow of images, preload all the images in the 3rd hidden frame

137

Animation (2)

Setting up the three frames

<HTML>

<HEAD>

<TITLE>Frame Animation</TITLE><HEAD>

<SCRIPT LANGUAGE="JavaScript">

function loadTime () {

self.frames["control"].animate();

}

</SCRIPT>

</HEAD>

<FRAMESET ROWS="80%, *" onLoad = "loadTime()">

<FRAMESET COLS="70%, *" >

<FRAME SRC="animate2.htm" NAME="control" >

<FRAME SRC="dummy.htm" NAME="output">

</FRAMESET>

<FRAMESET COLS="100%">

<FRAME SRC="picturecache.html" NAME="cache">

</FRAMESET>

</FRAMESET>

<NOFRAME>

This demo requires Netscape 3.0.

</NOFRAME>

</HTML>

138

Animation (3a) The animate frame:<HTML><HEAD><TITLE>Frame Animation</TITLE><SCRIPT>pictureShow = new Array ("p0.gif","p1.gif", "p2.gif", "p3.gif","p4.gif", "p5.gif") counter = 0thisone=0 function animate () {

if (counter < 20){parent.frames["output"].document.open();Temp = '<IMG SRC="' + pathOnly (location.href) +pictureShow[thisone] + '">'parent.frames["output"].document.write (Temp)parent.frames["output"].document.close()counter++thisone = counter%6ret = setTimeout ("animate()", 800)

}}

139

Animation (3b)

function pathOnly (InString) {

LastSlash=InString.lastIndexOf ('/', InString.length-1)

OutString=InString.substring (0, LastSlash+1)

return (OutString);

}

140

Animation (4)

The hidden frame simply consists of a series of images to be loaded.<IMG SRC=“p0.gif”> <IMG SRC=“p1.gif”><IMG SRC=“p2.gif”><IMG SRC=“p3.gif”><IMG SRC=“p4.gif”><IMG SRC=“p5.gif”>

141

Animation -- Other Options

Pros ConsJava Applet Fast, Control of size

and speedJava programmingbackground, Browser support

Client Pull Easy, Speed reasonable Can't just reload the imageServer Push In-place image update CGI-bin server access, CGI

scriptGIF 89a Easy, Speed reasonable Animator GIF builder

142

Visual Effects -- Fading

Need to:– setup an array to hold the color values to fade

through (i.e., fade in or fade out)– use a delay function to pause between color

changes (timerDelay() is used instead of setTimerOut() because the lowest resolution for the latter is about 1/3 sec, too long fading.)

Can setup the fading of the entire window or just a frame

143

Fading<HTML><HEAD><TITLE>Fade In Demo</TITLE><SCRIPT LANGUAGE="JavaScript">

function fadeOut () { timerDelay (20000) // delay between fade in

and fade out var Count; for (Count = Colors.length; Count >= 0;

Count--) { BGColor = Colors[Count]

+Colors[Count]+ Colors[Count] document.bgColor=BGColor; timerDelay (10); // change this alter

delay }}

function timerDelay(Delay) { var Count; for (Count=0 ; Count < Delay; Count++){} return;}Colors = new Array ("11", "22", "33", "44", "55", "66", "77","88",

"99", "aa", "bb", "cc", "dd", "ee", "ff")</SCRIPT></HEAD><BODY bgColor="#000000"

onLoad="fadeOut()"><H1 ALIGN=CENTER>Hello there!</H1><P>fade out</P></BODY></HTML>

144

More Features

JavaScript Library: ability to define a separate page for the JavaScript program– <SCRIPT SRC=“library.js”>

js extension do not need </SCRIPT> tag can include JavaSript code in <SCRIPT> and </SCRIPT> tags

– new <NOSCRIPT>and </NOSCRIPT> tags contents ignored by JavaScript but processed as HTML

145

More Features (2)

New event handlers typeof operator Form elements type property Extending objects

– built-in or user-defined objects

146

Why Custom Objects?

Consider the alternatives:– create individual variables or arrays for storing,

say, students.=> not flexible and can be complicated when

many students are involved Custom object definition allows one to

– associate properties– associate methods

147

Objects & Methods A method is a function associated with an object

(defined the same way you define a function) To associate the function with an existing object:

– object.methodname = function_name

where object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.

Can then call the method in the context of the object as follows: – object.methodname(params)

148

Constructor Function Defines the name, initial properties, and initial

methods of an object Has the same name as the name of the object Example:

function Student () {this.name = ““; // this = current objectthis.ss = “000-00-0000”;this.gpa = 0.0;

}aStudent = new Student(); // instantiate a new objectaStudent.name = “John Doe”;

149

Constructor Function (2)

Example:FileName: method.htm

<script>

function pretty_print(string) {

document.write("<HR><P>" + string)

}

function displayCar() {

var result = "A Beautiful " + this.year

+ " " + this.make + " " + this.model;

pretty_print(result)

}

function car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; this.displayCar = displayCar; // without ()}

car1 = new car("Eagle", "Talon TSi", 1993, "rand");

car2 = new car("Nissan", "300ZX", 1992, "ken")

car1.displayCar()car2.displayCar()

</script>

150

The prototype Property To add properties or methods to an already

instantiated object, use the prototype property. Syntax:

objectType.prototype.newProperty = defaultValue; Once added, all instances of the object type have the

new property. Example:

aStudent = new Student();Student.prototype.major= ““;aStudent.major = “Applied Computer Science”

151

The prototype Property (2)

Can also associate properties and methods with built-in objects

Example:FileName: prototype.htm<script>function myGetMonthStr() {

var monthArr = new Array("Jan", "Feb", "Mar", "Apr", "May","Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

return monthArr[this.getMonth()];}Date.prototype.getMonthStr = myGetMonthStr;var aDate = new Date();alert(aDate.getMonthStr());</script>

152

JavaScript vs. Java

JavaScript – interpreted (not

compiled) by client

– object-based (code uses built-in, extensible objects, but no classes or inheritance)

– code integrated with, and embedded in HTML.

Java– compiled on server before

execution on client

– object-oriented (applets consist of object classes with inheritance)

– applets distinct from HTML (accessed from HTML pages)

153

JavaScript vs. Java (2)

JavaScript– variable data types not

declared (loose typing)

– dynamic binding (object references checked at run-time)

– security: cannot write to hard disk

– no graphics library, no

threads, no networking

Java– variable data types must be

declared (strong typing)

– static binding (object references must exist at compile-time)

– security: multilevel control

– graphics library (AWT), threads, networking (sockets, RMI, etc.)

154

Connecting to Java

JavaScript now shares a closer relationship to Java– document.appletName property

<APPLET CODE=xyz.class NAME=xyz WIDTH=60 HEIGHT=30>

<PARAM NAME=label VALUE=xyz> </APPLET>

– here, document.xyz or document.applets[0] if it is the 1st applet.

155

Connecting to Java (2)

– Public variables of an applet are available in JavaScript

– Static methods and properties are available in JavaScript as methods and properties of the applet object

– Can get and set property values– Can call methods that return string, numeric,

and boolean values– others ...

156

Exercises

See the accompanying JavaScript course page

for exercises, solutions, sample programs, and related links

157

References

Client-Side JavaScript Guide, Netscape Communications Inc., 1998

Client-Side JavaScript Reference, Netscape Communications Inc., 1998

Hall, M., Core Web Programming, Prentice-Hall, 1998. Voodoo’s Introduction to JavaScript, 1998.