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

Post on 21-Jan-2016

214 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

Introduction to JavaScript

Presented by

Dr. Billy Lim

Developed by

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

Illinois State University

From the InfoTech Internet/Intranet Series

2

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

3

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

platform, WWW scripting language adopted by Netscape and allies.

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

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

4

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

5

Server Based Processing

User’s InputServer

Processing

Client (browser) Server

6

Client Based Processing

User’s Input Server Processing

Client (browser) Server

JavaScriptProcessing

7

Uses of JavaScript

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

8

JavaScript and Navigator (and IE) versions

Navigator version Default JavaScript version <SCRIPT> tags supported Navigator earlier than 2.0 JavaScript not supported None

Navigator 2.0, I.E., 3.0a JavaScript 1.0 <SCRIPT LANGUAGE="JavaScript">

Navigator 3.0, IE 3.0b JavaScript 1.1 <SCRIPT LANGUAGE = "JavaScript1.1"> and all earlier versions

Navigator 4.0-4.05, IE 4.0 JavaScript 1.2 <SCRIPT LANGUAGE = "JavaScript1.2"> and all earlier versions

Navigator 4.06-4.7, IE 5.0 JavaScript 1.3 <SCRIPT LANGUAGE = "JavaScript1.3"> and all earlier versions

IE 5.0 (partially) JavaScript 1.4 <SCRIPT LANGUAGE = "JavaScript1.4"> and all earlier versions

Navigator 6, IE 5.5-6.0 JavaScript 1.5 <SCRIPT LANGUAGE = "JavaScript1.5"> and all earlier versions

Note: Microsoft’s version is called JScript Official standard is called ECMAScript

9

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>

10

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>

Also, <script type="text/javascript">

11

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

12

write Method

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

Examples:<script>counter = 10;document.write(counter);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

13

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

14

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); // parse aString2 into an int numSalary = numSalary + 500;

15

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

16

JavaScript Debugging

In Firefox, Netscape, and Mozilla, type javascript: (on the location field) to get the console window so that you can see the error messages generated. Also, go to Error Console under Tools menu.

17

JavaScript Debugging (2)

In Chrome, go to Tools > Developer Tools. The window should display the error, as shown below

18

JavaScript Debugging (3)

In IE, when there is a script error on a page, a message appears on the bottom left corner. Double click on it to see the error.

19

JavaScript Debugging (4)

Firebug extension for Firefox (http://www.joehewitt.com/software/firebug/)

20

Language Features

21

JavaScript vs. C/C++ Similarities (apply to Java too)

– 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

22

Data Types

Numbers– 1, 3.14159, -99

Logical (Boolean) values– true or false (these two are the literal values that you

use to test the truth value of a logical expression) Strings

– “hello”, ‘hello’ null

– special keyword denoting null value

23

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.'

Escape character for single quote

24

Variables

You use variables to hold values in your application.– Syntax:var Variablename ; // var => local variable; Otherwise, the variable is global

var Variablename = value;

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 ”

25

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

26

Operators

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

++ (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

27

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

28

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’

conditionReturned if true Returned if false

29

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 () [] .

30

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

31

Statements

Comments Variable Declaration / Assignment Conditionals Loops

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

with statement Function Definition

32

Comments

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

Line 2.....

Line 3 */

33

Conditionals

Syntax

if (condition) {

statements

} [else { else statements

}]

Note: else part is not required; [ ] signifies that it is optional

Examples

<script>var marriedCount = 0;var singleCount = 0;status = prompt("What is your status (0 or 1)?")if (status == 1) { deduction = 500; marriedCount++;} else { deduction = 100; singleCount++;}alert("Your deduction is: " + deduction);</script>

34

Loops – for

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

statements

}

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

document.write(i);

}

Output:???

35

Loops – for-in 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>

36

Loops – while

Syntaxwhile (condition) { statements

} Example

n = 0;x = 0;while ( n < 3 ) { n ++ ;

x = x + n;document.write(n,x);

}

Output:1 12 33 6

37

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]) { // param’s are optional statements

} Example

// Takes 2 values and returns the smaller of the twofunction findMin (value1, value2) {

if (value1 < value2) return (value1);

else return (value2);

}answer = findMin(50,50); // function callalert("Your answer is: " + answer);

Output:???

38

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>

39

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)

40

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)

41

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

42

Arrays (Cont...)

Example:

FileName: Array-with-ForIn.htm

// This prints only the defined values of the array

<script>

for (i in anArray)

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

</script>

43

Arrays (Cont...) Other syntax of defining arrays: // TestOtherArraySyntax.htm

<script>function compare(a,b) {

return a-b;}anArray = new Array("Freshman","Sophomore","Junior","Senior");anArray2 = ["Computer Science","Mathematics","Accounting","Biology","Political Science"];anArray3 = [10, 300, 20, 40];for (i in anArray)

document.write("anArray at "+i+" = "+anArray[i] +"<BR>");document.write("<hr>");anArray2.sort(); // do sorting of stringsfor (i in anArray2)

document.write("anArray at "+i+" = "+anArray2[i] +"<BR>");document.write("<hr>");anArray3.sort(); // does not sort the numbers!for (i in anArray3)

document.write("anArray at "+i+" = "+anArray3[i] +"<BR>");document.write("<hr>");anArray3.sort(compare);for (i in anArray3)

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

44

Arrays (Cont...)

JavaScript’s Object Model (later on this) consists of many arrays that allow you to manipulate the objects on a web document.

For example,– frames (from window) // window.frames[0]….

– anchors (from document) // document.anchors[0]….

– applets (from document) // document.applets[0]….

– forms (from document) // document.forms[0]….

– images (from document) // document.images[0]….

– layers (from document) // document.layers[0]….

– links (from document) // document.links[0]….

– elements (from form) // document.forms[0].elements[0]….

– options (from select) // document.forms[0]. elements[0].options[0]….

45

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 ...

46

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.

47

document.images[0]document.images[1]document.images[2]

document.forms[0].elements[0]document.forms[0].elements[1]document.forms[0].elements[2]document.forms[0].elements[3]document.forms[0].elements[4]

document.links[0]document.links[1]document.links[2]

48

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

49

Object Hierarchy (DOM)

Built-in Objects:• String• Date• Array• Boolean• Math

50

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.

51

Objects at WorkFileName: firstFormEvent.htm<HEAD><SCRIPT LANGUAGE="JavaScript">function compute(aForm) { if (confirm("Are you sure?")) aForm.result.value = eval(aForm.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>

52

Objects at Work

Dissection of the example– “this” refers to the object in question– this.form refers the form that the object in question is

defined in Thus, “compute(this.form)” calls the compute function and

passes the form that the button object resides in to the function. Other means of passing:

– “compute()” => Here, no form is passed into the function. Thus, to access result, one needs document.MyForm.result.value instead of form.result.value (the same is true for expr)

– “compute(this)” => Here, the button object is passes into the function. This would not be meaningful since the button object itself in not needed in the function. The two text fields are the ones that are needed.

53

Document Object: UsegetElementById()

<html><head><script type="text/javascript">function getElement() {

var x=document.getElementById("myHeader")alert("I am a " + x.tagName + " element")

}function getElement2() {

var x=document.getElementsByName("myHeader2") // x gets an array of elementsalert("I am a " + x[0].tagName + " element")

}</script></head><body><h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1><h2 name="myHeader2" onclick="getElement2()">Click to see what element I am!</h1></body></html>

Source: Modified from Shin’s JavaScript

54

Document Object: UsegetElementsByName()

<html><head><script type="text/javascript">function getElements() {

var x=document.getElementsByName("myInput")alert(x.length + " elements!")

}</script></head><body><input name="myInput" type="text" size="20"><br /><input name="myInput" type="text" size="20"><br /><input name="myInput" type="text" size="20"><br /><br /><input type="button" onclick="getElements()" value="How many elements named 'myInput'?"></body></html>

Source: Shin’s JavaScript

55

Featured Objects

(in alphabetical order)

56

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

57

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

58

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>

59

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() // current moment– dateObjectName = new Date(year, month, day, hours,

minutes, seconds)

Properties– None.

60

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.

61

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

62

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

Better to use getFullYear()– This gives a 4-digit year

Need this addition in Netscape.IE will return the correct year

63

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)

64

Document Object (2)

Properties– alinkColor reflects the ALINK attribute – anchors is an array reflecting all the anchors in a document – applets is an array of objects corresponding to the applets in a document in source order. – bgColor reflects the BGCOLOR attribute – cookie specifies a cookie (string value representing all of the cookies associated with this

document)– 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

65

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 = ...

66

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)

67

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

68

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

69

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.

70

Frames (2)

Frames HTML Syntax:

<HTML>

<HEAD>

</HEAD>

<FRAMESET>

</FRAMESET>

</HTML>

The Frame definitions go between the frameset tags

71

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,*">

</frameset>

<frameset rows="30%,70%>

</frameset>

72

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

73

Frames (5)

Sample frame scripting

<html>

<frameset rows="50%,*">

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

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

</frameset>

</html>

74

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>

Hypertext reference with a “Target” tag:

<h3>Correct Answers</h3>

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

75

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)

76

Hidden Object (cont’d)

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>

77

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”;

78

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

79

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 document.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/"

80

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)

81

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 radio button, document.forms[0].radioName[1] is the second, etc.

– or myForm.radioName[0], etc. // access a form using its name

82

Radio Object (2) Properties

– checked lets you programatically select a radio button and check if a radio button is checked or not.

– 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

This means that you can check which radio button is selected by doing:

if (myForm.musicChoice[0].checked == true) … // first radio button is checked

83

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>

84

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

85

Select Object (Options Array)

A selection (“drop-down”) 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)

86

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

87

Select Object (Options Array) (3) 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>

88

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.

89

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) last_name.charAt(1) // gives “c” (not “S”)

Question: What if you need the 2nd “e” on the string? (Answer: check out the API for a method. Let’s see …)

90

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)” method="get" action="http://was6.itk.ilstu.edu:9080/itk/EchoAll"><INPUT TYPE="TEXT" NAME="Box" VALUE=""><INPUT TYPE="submit"> </form>

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

91

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

92

Text Object (2) 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>

93

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

94

Textarea Object (2)

Event handlers– onBlur – onChange – onFocus – onSelect

Property of– form

95

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!!!

96

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

97

Window Object (3) Methods

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

Event handlers– onLoad – onUnload

Property of– None.

98

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>

99

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>

100

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>

101

Event Handling

102

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.

103

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

104

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.

105

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

106

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

107

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

108

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.

109

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>

110

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

alert("OK")

} else {

alert("Input value " + strval + " is out of range");

}

}</SCRIPT>

</HEAD>

<BODY>

<P>

<HR><FORM NAME="myform"></P>

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

<P><BR>

<INPUT TYPE=“button“onClick="checkit()“></FORM>

<HR></P>

</BODY>

</HTML>

111

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.

112

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

113

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. Shin, S., JavaScript Basics, www.javapassion.com.

top related