Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr...

30
Programming for WWW Programming for WWW (ICE 1338) (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko .AT. i cu . ac.kr Information and Communications University (ICU)

Transcript of Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr...

Page 1: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

Programming for WWWProgramming for WWW(ICE 1338)(ICE 1338)

Lecture #5Lecture #5 July 7, 2004

In-Young Koiko .AT. icu.ac.kr

Information and Communications University (ICU)

Page 2: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 2 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

AnnouncementsAnnouncements

Submit your Submit your homework#1homework#1 ( (a URLa URL or or HTML HTML source)source)

7 Project teams have been formed7 Project teams have been formed Project proposal due: Project proposal due: Friday July 9Friday July 9thth

Please prepare for the presentation of your Please prepare for the presentation of your proposal (5-10 minutes per each team)proposal (5-10 minutes per each team)

A sample ‘A sample ‘reference sitereference site’’ http://www.javacommerce.com/tutorial/notes/http://www.javacommerce.com/tutorial/notes/

javascript/javascript/ch23.htm#TheUnofficialJavaScriptResourceCenter ch23.htm#TheUnofficialJavaScriptResourceCenter

Page 3: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 3 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Homework #2Homework #2

Due date: Due date: July 21stJuly 21st Develop a Web wrapperDevelop a Web wrapper: Wrap any Web site : Wrap any Web site

that accepts a query and returns a customized that accepts a query and returns a customized resultresult Make a program that accepts a Make a program that accepts a user inputuser input, directly , directly

connectsconnects to the Web site and to the Web site and retrieve resultsretrieve results The program must include the The program must include the query translationquery translation and and

result parsingresult parsing features features Submit a report (hard copy) Submit a report (hard copy) that explains the that explains the

wrapping mechanismwrapping mechanism and and structurestructure of your Web of your Web wrapper programwrapper program

Page 4: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 4 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Review of the Previous LectureReview of the Previous Lecture

Basic UNIX CommandsBasic UNIX Commands More on Web-based Information More on Web-based Information

IntegrationIntegration JavaScript (Definition)JavaScript (Definition)

Page 5: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 5 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Contents of Today’s LectureContents of Today’s Lecture

More on JavaScript (Text Chap. 6 – 8)More on JavaScript (Text Chap. 6 – 8) Document Object Model HTMLDocument Object Model HTML Data typesData types OperatorsOperators Pattern matchingPattern matching Event handlingEvent handling

Page 6: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 6 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

General Syntax of JavaScriptGeneral Syntax of JavaScript

Direct embedding of a JavaScript code:Direct embedding of a JavaScript code:<script language = "JavaScript"><script language = "JavaScript">

-- JavaScript script –-- JavaScript script –</script></script>

Indirect JavaScript specification:Indirect JavaScript specification:<script language = "JavaScript" src = "myScript.js“<script language = "JavaScript" src = "myScript.js“//>>

Identifier form: begin with a letter or underscore,Identifier form: begin with a letter or underscore, followed by any number of letters, underscores, followed by any number of letters, underscores, and digitsand digits

Case sensitiveCase sensitive Comments: both Comments: both //// and and /* … *//* … */ Manual: Manual: http://http://devedge.netscape.com/central/javascriptdevedge.netscape.com/central/javascript//

Page 7: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 7 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

An ExampleAn Example<html><html><head><title> A switch statement </title></head><head><title> A switch statement </title></head><body><body><script type = "text/javascript"><!--<script type = "text/javascript"><!--var bordersiz = prompt("Select a table border size \n" +var bordersiz = prompt("Select a table border size \n" + "0 (no border) \n 1 (1 pixel border) \n" +"0 (no border) \n 1 (1 pixel border) \n" + "4 (4 pixel border) \n 8 (8 pixel border) \n");"4 (4 pixel border) \n 8 (8 pixel border) \n");switch (bordersize) {switch (bordersize) { case "0": case "0": document.writedocument.write("<table>"); break;("<table>"); break; case "1": case "1": document.writedocument.write("<table border = '1'>"); break;("<table border = '1'>"); break; case "4": case "4": document.writedocument.write("<table border = '4'>"); break;("<table border = '4'>"); break; case "8": case "8": document.writedocument.write("<table border = '8'>"); break;("<table border = '8'>"); break; default: default: document.writedocument.write("Error - invalid choice: ", bordersize, ("Error - invalid choice: ", bordersize,

"<br />");"<br />");}}document.writedocument.write("<caption>Sample Table</caption>");("<caption>Sample Table</caption>");document.writedocument.write("<tr>",("<tr>","<th> American Conference </th>","<th> American Conference </th>","<th> National Conference </th>","<th> National Conference </th>","</tr>", "</tr>", …);…);-->--></script></script></body></body></html></html> AW lecture notes

Page 8: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 8 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Document Object Model HTMLDocument Object Model HTML

““A platform- and language-neutral interface that allows A platform- and language-neutral interface that allows programsprograms and and scriptsscripts to dynamically to dynamically access and updateaccess and update the the contentcontent, , structurestructure and and stylestyle of documents” of documents”

<html><html><head><head> <title>My Document</title><title>My Document</title></head></head><body><body> <h1><h1>HeaderHeader</h1></h1> <p>Paragraph</p><p>Paragraph</p></body></body></html></html>

http://www.mozilla.org/docs/dom/technote/intro/

var header = document.var header = document.getElementsByTagNamegetElementsByTagName("H1").("H1").itemitem(0);(0);

header.header.firstChildfirstChild..datadata = "A dynamic document"; = "A dynamic document";

Page 9: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 9 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Document Object Model HTML Document Object Model HTML (cont.)(cont.)

Under development by w3c since the mid-90sUnder development by w3c since the mid-90s DOM 0DOM 0 is supported by all JavaScript browsers is supported by all JavaScript browsers DOM 2DOM 2 is the latest approved standard is the latest approved standard Nearly completely supported by NS6Nearly completely supported by NS6 IE6’s support is lacking some important thingsIE6’s support is lacking some important things

The DOM is an abstract model that defines the The DOM is an abstract model that defines the interface interface between HTML documents and application programsbetween HTML documents and application programs

It is an OO model - document elements are objectsIt is an OO model - document elements are objects

A language that supports the DOM must have a binding A language that supports the DOM must have a binding to the DOM constructsto the DOM constructs In the JavaScript binding, HTML elements are represented as In the JavaScript binding, HTML elements are represented as

objects and element attributes are represented as propertiesobjects and element attributes are represented as propertiese.g., e.g., <input type = "text" name = "address"><input type = "text" name = "address">

AW lecture notes

Page 10: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 10 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

DOM SpecificationDOM Specification http://www.w3.org/TR/DOM-Level-2-HTML/html.htmlhttp://www.w3.org/TR/DOM-Level-2-HTML/html.html e.g.,e.g.,

Page 11: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 11 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

DOM Element Access in JavaScript

<form action = ""><form action = ""> <input type = "button" name = "pushMe"><input type = "button" name = "pushMe">

</form></form>

1.1. DOM address: DOM address: document.forms[0].element[0]document.forms[0].element[0] Problem: A change in the document could invalidate this addressProblem: A change in the document could invalidate this address

2.2. Element namesElement namese.g.,e.g., <form name = "myForm" action = ""><form name = "myForm" action = ""> <input type = "button" name = "pushMe"><input type = "button" name = "pushMe"> </form></form>

document.myForm.pushMedocument.myForm.pushMe Requires the element and all of its ancestors (except body) to have Requires the element and all of its ancestors (except body) to have

name attributesname attributes Problem: Strict standard does not allow form elements to have namesProblem: Strict standard does not allow form elements to have names

3.3. getElementByIdgetElementById Method Methode.g., e.g., <form action = ""><form action = ""> <input type = "button" id = "pushMe"><input type = "button" id = "pushMe"> </form></form> document.getElementById("pushMe")document.getElementById("pushMe")

AW lecture notes

Page 12: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 12 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Screen OutputsScreen Outputs The model for the browser The model for the browser display display

windowwindow is the is the WindowWindow object object Properties:Properties:

window.documentwindow.document window.frameswindow.frames window.screenLeftwindow.screenLeft window.screenTopwindow.screenTop ……

Methods:Methods: alert: alert: confirmconfirm promptprompt

Page 13: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 13 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Primitive Data TypesPrimitive Data Types Primitive Data Types: Primitive Data Types: nnumberumber, , sstringtring, , bbooleanoolean, ,

uundefinedndefined or or nnullull Wrapper classes: Wrapper classes: NumberNumber, , StringString, , BooleanBoolean Boolean valuesBoolean values: : ttruerue (non-zero, non-empty string) (non-zero, non-empty string)

and and falsefalse (otherwise) (otherwise) Null valueNull value:: nullnull Undefined valueUndefined value:: undefinedundefined, NaN, NaN

All numeric values are stored in All numeric values are stored in double-double-precisionprecision floating pointfloating point

String literals are delimited by either String literals are delimited by either ' ' or or "" Can include Can include escape sequencesescape sequences (e.g., \t) (e.g., \t) In the cases of In the cases of NumberNumber and and StringString, primitive, primitive

values can be treatedvalues can be treated as if they were objectsas if they were objects

Page 14: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 14 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

VariablesVariables

Variables are dVariables are dynamically typedynamically typed – any – any variable can be used for anything variable can be used for anything (primitive value or reference to any object)(primitive value or reference to any object) The The interpreter determinesinterpreter determines the type of a the type of a

particularparticular occurrence of a variableoccurrence of a variable Variables can be either Variables can be either implicitlyimplicitly or or

explicitlyexplicitly declareddeclared e.g.1,e.g.1, sum = 0; today = “Wed”; flag = false;sum = 0; today = “Wed”; flag = false;

e.g.2,e.g.2, var sum = 0,var sum = 0, today = “today = “WedWed",", flag;flag;

Page 15: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 15 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Operators and StatementsOperators and Statements

Numeric, Boolean, relational and string Numeric, Boolean, relational and string operators are similar to C-based operators are similar to C-based languageslanguages

Length of a string: Length of a string: stringstring.length.length The The typeoftypeof operator operator::

Returns "number", "string", or "boolean" for Returns "number", "string", or "boolean" for primitivesprimitives

RReturns "object" for objects and nulleturns "object" for objects and null Control statements are similar to Java – Control statements are similar to Java –

if, switch, while, for, doif, switch, while, for, do

Page 16: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 16 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Numeric OperationsNumeric Operations

All All numeric numeric operations are in operations are in double precisiondouble precision The The MathMath Object Object

Methods: Methods: floorfloor, , roundround, , maxmax, , minmin, , sinsin, , etc.etc. The The NumberNumber Object Object

PProperties: roperties: MAX_VALUEMAX_VALUE, , MIN_VALUEMIN_VALUE, , NaNNaN, , POSITIVE_INFINITYPOSITIVE_INFINITY,, NEGATIVE_INFINITYNEGATIVE_INFINITY, , PIPI

Methods:Methods: toStringtoString,, valueOfvalueOf,, toFixedtoFixed((fractNofractNo))e.g., e.g., 0 .126.tofixed(2)0 .126.tofixed(2) returns "0.13“ returns "0.13“

An operation that creates overflow returns An operation that creates overflow returns NaNNaN NaN is not == to any number, not even itselfNaN is not == to any number, not even itself Test for it with Test for it with isNaNisNaN((numnum))

Page 17: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 17 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Data Type CoercionsData Type Coercions Type CoercionsType Coercions: Implicit type conversion : Implicit type conversion

between data types due to compatibilitybetween data types due to compatibilitye.g., e.g., 5 + 1.235 + 1.23 6.23, 6.23, 5 + “6” + 75 + “6” + 7 “567”, “567”,

5 == “5”5 == “5” true true Strict relational operators that disallow type Strict relational operators that disallow type

coercions: coercions: ====== and and !===!=== Operators (other than +, ===, and !===) coerce Operators (other than +, ===, and !===) coerce

strings to numbers – e.g., strings to numbers – e.g., 5 – “6” + 75 – “6” + 7 6 6 Conversions from strings to numbers that do Conversions from strings to numbers that do

not work return NaNnot work return NaN Conversion functionsConversion functions: : parseIntparseInt(string)(string) and and

parseFloatparseFloat(string)(string)

Page 18: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 18 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Object Creation and ModificationObject Creation and Modification

Basic Object CreationBasic Object Creation var myObj = new Object();var myObj = new Object(); The new object has no properties The new object has no properties –– a blank object a blank object

Properties can be added to an object, any timeProperties can be added to an object, any timeee.g., .g., myObj.color = “blue”; myObj.flag = false;myObj.color = “blue”; myObj.flag = false;

Properties can be accessed in array notationProperties can be accessed in array notatione.g., e.g., var property1 = myObj[“color"]var property1 = myObj[“color"];;

If you try to access a property that does not exist, you If you try to access a property that does not exist, you get get undefinedundefined

Properties can be deleted with Properties can be deleted with deletedeleteee.g., .g., delete myObj.flag;delete myObj.flag;

Properties can iteratedProperties can iteratede.g., e.g., for (var prop in myObj)for (var prop in myObj)

document.write(myObj[prop] + "<br/>");document.write(myObj[prop] + "<br/>"); AW lecture notes

Page 19: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 19 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

ArraysArrays Array length is Array length is dynamicdynamic Array objects can be created in two ways, with Array objects can be created in two ways, with

new, or by assigning an array literalnew, or by assigning an array literalvar myList = new Array(24, "bread", true);var myList = new Array(24, "bread", true);var myList2 = [24, "bread", true];var myList2 = [24, "bread", true];var myList3 = new Array(24);var myList3 = new Array(24);

The length of an array is the highest subscript to The length of an array is the highest subscript to which an element has been assigned, plus 1which an element has been assigned, plus 1

myList[122] = "bitsy"; myList[122] = "bitsy"; // // length is 123 length is 123 You can set the array length - You can set the array length - myList.length = 150;myList.length = 150; Only assigned elements take spaceOnly assigned elements take space Array methods: Array methods: join, concat, sort, reverse, join, concat, sort, reverse, ……AW lecture notes

Page 20: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 20 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

FunctionsFunctionsfunction function_name([formal_parameters]) {function function_name([formal_parameters]) {

-- body –-- body – }}

If there is no return, or if return has no parameter, If there is no return, or if return has no parameter, undefinedundefined is returned is returned

Functions are objectsFunctions are objects, so variables that reference them , so variables that reference them can be treated as other object references (can be can be treated as other object references (can be passed as parameters, assigned to variables, and be passed as parameters, assigned to variables, and be elements of an array)elements of an array)

e.g., If fun is the name of a function,e.g., If fun is the name of a function, ref_fun = fun;ref_fun = fun; /* Now ref_fun is a reference to fun */ /* Now ref_fun is a reference to fun */ ref_fun();ref_fun(); /* A call to fun */ /* A call to fun */

All function definitions are in the head of the HTML All function definitions are in the head of the HTML document, and all calls are in the bodydocument, and all calls are in the body

AW lecture notes

Page 21: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 21 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Functions Functions (cont.)(cont.)

All variables that are either All variables that are either implicitly declaredimplicitly declared or or explicitly declared outside functionsexplicitly declared outside functions are are globalglobal

Variables explicitly declared in a function are Variables explicitly declared in a function are locallocal

Parameters are Parameters are passed by valuepassed by value There is There is no type checkingno type checking of parameters, of parameters, nor is nor is

the number of parameters checkedthe number of parameters checked (excess (excess actual parameters are ignored, excess formal actual parameters are ignored, excess formal parameters are set to undefined)parameters are set to undefined)

All parameters are sent through a property All parameters are sent through a property array, array, argumentsarguments, which has the , which has the lengthlength propertyproperty

Page 22: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 22 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

A Function ExampleA Function Example<html><html><head> <title> Parameters </title><head> <title> Parameters </title><script type = "text/javascript"><script type = "text/javascript"><!--<!--function params(a, b) {function params(a, b) { document.write("a = " + a + ", b = " + b + "<br />");document.write("a = " + a + ", b = " + b + "<br />"); document.write(“Passed ", document.write(“Passed ", arguments.lengtharguments.length, ,

" parameter(s) <br />");" parameter(s) <br />"); document.write("Parameter values are: <br />");document.write("Parameter values are: <br />"); for (var arg = 0; arg < arguments.length; arg++)for (var arg = 0; arg < arguments.length; arg++) document.write(document.write(arguments[arg]arguments[arg], "<br />");, "<br />"); document.write("<br />");document.write("<br />");}}// -->// --></script></script></head></head><body><body><script type = "text/javascript"><script type = "text/javascript">params("Mozart");params("Mozart");params("Mozart", "Beethoven");params("Mozart", "Beethoven");params("Mozart", "Beethoven", "Tchaikowsky");params("Mozart", "Beethoven", "Tchaikowsky");</script></script></body></body></html></html> AW lecture notes

Page 23: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 23 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

ConstructorsConstructors Used to initialize objects, but actually create the propertiesUsed to initialize objects, but actually create the properties

function planefunction plane(newMake, newModel, newYear){ (newMake, newModel, newYear){ this.make = newMake;this.make = newMake; this.model = newModel;this.model = newModel;

this.year = newYear;this.year = newYear; }}a myPlane = a myPlane = new planenew plane("Cessna", "Centurnian", "1970");("Cessna", "Centurnian", "1970");

Can also have method propertiesCan also have method propertiesfunction function displayPlanedisplayPlane() {() {

document.write("Make: ", this.make, "<br />");document.write("Make: ", this.make, "<br />"); document.write("Model: ", this.model, "<br />");document.write("Model: ", this.model, "<br />"); document.write("Year: ", this.year, "<br />");document.write("Year: ", this.year, "<br />"); }} this.display = displayPlane;this.display = displayPlane;

AW lecture notes

Page 24: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 24 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Pattern MatchingPattern Matching Patterns are based on those of PerlPatterns are based on those of Perl Pattern-matching operations are methods of the String Pattern-matching operations are methods of the String

objectobject search(pattern)search(pattern): Returns the position in the object : Returns the position in the object

string of the pattern; returns -1 if it failsstring of the pattern; returns -1 if it failsvar str = "Gluckenheimer";var str = "Gluckenheimer";var position = str.search(/n/); var position = str.search(/n/); /* position is now 6 */ /* position is now 6 */

replace(pattern, string)replace(pattern, string): Finds a substring that : Finds a substring that matches the pattern and replaces it with the stringmatches the pattern and replaces it with the string

var str = "Some rabbits are rabid";var str = "Some rabbits are rabid";str.replace(/rab/gi, "tim");str.replace(/rab/gi, "tim");str is now "Some timbits are timid"str is now "Some timbits are timid"$1 and $2 are both set to "rab“$1 and $2 are both set to "rab“

Regular Expressions: Regular Expressions: http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/regexp.html http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/regexp.html

AW lecture notes

Page 25: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 25 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

A Pattern Matching ExampleA Pattern Matching Example

<html><html><head> <title>Zip code tester</title><head> <title>Zip code tester</title><script type = "text/javascript"><script type = "text/javascript">function tst_zip_code(num) {function tst_zip_code(num) { var ok = num.var ok = num.search(/\d{3}-\d{3}/)search(/\d{3}-\d{3}/);; if (ok != 0) if (ok != 0) alert("An invalide zip code: " + num);alert("An invalide zip code: " + num);}}// -->// --></script></script></head></head><body><body><form><form><input type="text" class="text" <input type="text" class="text"

onBlur="onBlur="javascript:tst_zip_code(this.value)javascript:tst_zip_code(this.value)">"></form></form></body></body></html></html>

Page 26: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 26 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Events and Event HandlingEvents and Event Handling

An An eventevent is a notification that something is a notification that something specific has occurred, either with the browser or specific has occurred, either with the browser or an action of the browser useran action of the browser user

An An event handlerevent handler is a script that is implicitly is a script that is implicitly executed in response to the appearance of an executed in response to the appearance of an eventevent

The process of connecting an event handler to The process of connecting an event handler to an event is called an event is called registrationregistration

HTML Events: HTML Events: http://www.webdevelopersjournal.com/articles/jhttp://www.webdevelopersjournal.com/articles/jsevents1/jsevents1.htmlsevents1/jsevents1.html

Page 27: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 27 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

EventsEventsMouse Event Description

onmousedown A mouse button has been pressed

onmousemove The mouse has been moved

onmouseout The mouse pointer has left an element

onmouseover The mouse pointer has entered an element

onmouseup A mouse button has been released

onclick A mouse button has been clicked

ondblclick A mouse button has been double-clicked

Event Description

onblur An element loses focus

onerror An error occurs

onfocus An element gains focus

onload The document has completely loaded

onreset A form reset command is issued

onscroll The document is scrolled

onselect The selection of element has changed

onsubmit A form submit command is issued

Page 28: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 28 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Event HandlingEvent Handling

Event handlers can be specified in two ways:Event handlers can be specified in two ways:

1.1. By assigning the event handler script to an By assigning the event handler script to an event tag attributeevent tag attribute

ee.g., .g., <body onload="load_greeting();"><body onload="load_greeting();">

2.2. Event handlers can be specified by assigning Event handlers can be specified by assigning them to them to properties of the JavaScript objectsproperties of the JavaScript objects associated with the HTML elementsassociated with the HTML elements If the event handler is a function, just assign its If the event handler is a function, just assign its

name to the propertyname to the property

ee.g., .g., document.myForm.elements[0].onclick = document.myForm.elements[0].onclick = myHandler;myHandler;

No way to use parametersNo way to use parameters

Page 29: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 29 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

Event Handling Event Handling (cont.)(cont.)

The The focusfocus function puts the element in function puts the element in focus, which puts the cursor in the focus, which puts the cursor in the elementelement ee.g., .g.,

document.getElementById("phone").focus();document.getElementById("phone").focus(); The The selectselect function highlights the text in function highlights the text in

the elementthe element

Page 30: Programming for WWW (ICE 1338) Lecture #5 Lecture #5 July 7, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 7, 2004 30 Programming for WWW (Lecture#5) In-Young Ko, Information Communications University

JavaScript ReferenceJavaScript Reference

JavaScript Guide: JavaScript Guide: http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/index.html http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/index.html

JavaScript Reference Manual: JavaScript Reference Manual: http://devedge.netscape.com/central/javascript/http://devedge.netscape.com/central/javascript/

DOM HTML Specification: DOM HTML Specification: http://www.w3.org/TR/DOM-Level-2-HTML/html.htmlhttp://www.w3.org/TR/DOM-Level-2-HTML/html.html

Regular Expressions: Regular Expressions: http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/regexp.html\http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/regexp.html\

HTML Events: HTML Events: http://www.webdevelopersjournal.com/articles/jsevents1/jsevents1.htmlhttp://www.webdevelopersjournal.com/articles/jsevents1/jsevents1.html