javascript - computer scienceepl425/notes/slides10-javascriptxhtml-sebesta… · chapter 5 © 2010...

13
Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript !"#$% & "’%$ ()*++$ μ, -&# .$+%/0 JavaScript (core JavaScript) 1$234"5,% ,6%6)73# μ%$ +8))3(0 μ,29’:#, $#-%/,%μ7#:# /$% %’%3-0-:# 638 ,6%-47638# +, +/4"6- JS #$ $))&),6%’43;# μ, XHTML $4<,"$ 638 /$-$=34-*#3#-$% +, 7#$# 6)3&(9. Chapter 5 © 2010 by Addison Wesley Longman, Inc. 3 5.1 JavaScript Execution Environment - The JavaScript Window object represents the window in which the browser displays documents - The Window object provides the largest enclosing referencing environment for scripts - All global variables are properties of Window - Implicitly defined Window properties: - document - a reference to the Document object that the window displays - frames - an array of references to the frames of the document - Every Document object has: - forms - an array of references to the forms of the document - Each Form object has an elements array, which has references to the form’s elements - Document also has anchors, links, & images 4 Document Object Model (DOM) DOM provides an object model and an API for a (HTML) document. • One of the best ways to visualize the DOM for a web page is to use the DOM Inspector that comes with Mozilla browsers (plugin for Firefox) • Within the DOM, all page elements are placed in a treelike hierarchy: every HTML tag is a node within this tree, with subnodes and parent nodes every text portion is its own DOM node The DOM API supports methods to not only access elements in the DOM tree but also to add and remove elements.

Upload: lelien

Post on 08-Apr-2018

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1

JavaScript !"#

"$%&'" XHTML

2

Client-side JavaScript

• !"#$% & "'%$ ()*++$ µ, -&# .$+%/0 JavaScript (core

JavaScript)

• 1$234"5,% ,6%6)73# µ%$ +8))3(0 µ,29':#, $#-%/,%µ7#:#

/$% %'%3-0-:# 638 ,6%-47638# +, +/4"6- JS #$

$))&),6%'43;# µ, XHTML $4<,"$ 638 /$-$=34-*#3#-$%

+, 7#$# 6)3&(9.

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 3

5.1 JavaScript Execution Environment

- The JavaScript Window object represents the window in which the

browser displays documents

- The Window object provides the largest enclosing referencing

environment for scripts - All global variables are properties of Window

- Implicitly defined Window properties:

- document - a reference to the Document object that the window

displays - frames - an array of references to the frames of the document

- Every Document object has:

- forms - an array of references to the forms of the document

- Each Form object has an elements array, which has references to

the form’s elements - Document also has anchors, links, & images

4

Document Object Model (DOM)

• DOM provides an object model and an API for a (HTML) document.

• One of the best ways to visualize the DOM for a web page is to use the DOM Inspector that comes with Mozilla browsers (plugin for Firefox)

• Within the DOM, all page elements are placed in a treelike hierarchy:

– every HTML tag is a node within this tree, with subnodes and

parent nodes

– every text portion is its own DOM node

• The DOM API supports methods to not only access elements in the DOM tree but also to add and remove elements.

Page 2: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 5 Chapter 5 © 2010 by Addison Wesley Longman, Inc. 6

5.2 The Document Object Model

- DOM 0 is supported by all JavaScript-enabled browsers- no written specification - DOM 1 was released in 1998 - DOM 2 was released in 2000 - DOM 3 is the latest approved standard (2004)

- The DOM is an abstract model that defines the interface between HTML documents and application programs—an API - Documents in the DOM have a tree-like structure - A language that supports the DOM must have a binding to the DOM constructs

- In the JavaScript binding, HTML elements are represented as objects and element attributes are represented as properties e.g., <input type = "text" name = "address"> would be represented as an object with two properties, type and

name, with the values "text" and "address"

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 7

5.2 The Document Object Model

- Both IE8 and FX3 have ways to show the tree of a document

- See book p. 188 for the necessary steps for both browsers to get the tree of a given document

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> A simple table </title> </head> <body> <table border = "border"> <tr> <th> </th> <th> Apple </th> <th> Orange </th> </tr> <tr> <th> Breakfast </th> <td> 0 </td> <td> 1 </td> </tr> </table> </body></html>

8

Element access in JavaScript

• The elements of an XHTML document have

corresponding objects that are visible to an embedded

JavaScript script.

• The addresses of these objects are required both by the

event handling scripts and by the code for making

dynamic changes to documents.

Page 3: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 9

5.3 Element Access in JavaScript

- There are several ways to gain access to an XHTML form element. For example, take a document with just one form and one widget: <form action = "">

<input type = "button" name = "pushMe" />

</form>

1. We can use the DOM address of the XHTML element, i.e. the address of the JavaScript object associated with that element:

document.forms[0].element[0] Problem: document changes require changes in the JS code as well

2. Use element names – requires the element and all of its ancestors (except body) to have name attributes. Example:

<form name = "myForm" action = "">

<input type = "button" name = "pushMe“ />

</form>

document.myForm.pushMe

Problem: XHTML 1.1 spec doesn’t allow the name attribute on form

elements

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 10

5.3 Element Access in JavaScript (continued)

3. Use the getElementById Method (defined in DOM 1). Example:

<form action = ""> <input type = "button" id = "pushMe" /> </form> E.g. document.getElementById("pushMe")- The parameter to getElementById can be any expression evaluated to String.

4. Use of implicit arrays - Buttons in a group of checkboxes often share the same name (buttons in a radio button group always have the same name).

- Therefore, the names of the individual buttons cannot be used in their DOM addresses. - getElementById is an alternative but does not facilitate the search

of a group to see which button is checked. - An alternative is to use an implicit array that is associated with each checkbox and radio button group. - Checkboxes and radio buttons have an implicit array, which has their name, and which stores the DOM addresses of the individual buttons in the group.

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 11

<form id = "topGroup"> <input type="checkbox" name="toppings" value ="olives"> ... <input type ="checkbox" name ="toppings" value ="tomatoes"/></form>...

var numChecked = 0;var dom = document.getElementById("topGroup");for index = 0; index < dom.toppings.length; index++) if (dom.toppings[index].checked) numChecked++;

12

Events and Event Handling

• On important use of JavaScript and Web programming is to:– detect certain activities of the browser and the browser user

and provide computation when those activities occur

• The computations are specified with a special form of programming called event-driven programming:– In conventional programming, the code itself specifies the order

in which it is executed

– In event-driven programming, parts of the program are

executed at completely unpredictable times, often triggered by

user interactions with the executing program

• [Wikipedia] In computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—i.e., sensor outputs or user actions (mouse clicks, key presses) or messages from other programs or threads.

Page 4: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Events and Event Handling

• An event is a notification that something specific has occurred,

either with the browser or an action of the browser user

– Events are created by activities associated with specific HTML elements; e.g. the click event can be caused by the browser-user clicking a button or the link of an anchor tag

– Besides the event name, usually we need the specific HTML element that caused the event in order to decide who to handle it

• An event handler is a script that is implicitly executed in

response to the appearance of an event

• The process of connecting an event handler to an event is

called registration

• Events are JavaScript objects and their names are case

sensitive (only lowercase letters)

– Don’t use document.write in an event handler, because the

output may go on top of the display

13 Chapter 5 © 2010 by Addison Wesley Longman, Inc. 14

5.4 Events and Event Handling

- HTML 4.0 defined a collection of events that browsers implement and with which JavaScript can deal.

- These events are associated with XHTML tag attributes, which can be used to connect events to handlers

- Note: the same attribute can appear in several different tags e.g., the onclick attribute can be in <a> and <input>

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 15 Chapter 5 © 2010 by Addison Wesley Longman, Inc. 16

Page 5: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 17 Chapter 5 © 2010 by Addison Wesley Longman, Inc. 18

5.4 Events and Event Handling (continued)

- A text element gets focus in different ways:

1. When the user puts the mouse cursor over it and presses

the left button

2. When the user tabs to the element

- Only one text element can have focus at one time

- When a text element has focus, any keyboard input goes into

that element

- An element becomes blurred when another element gets focus

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 19

5.4 Event Handler registration- Event handlers can be registered in two ways in the DOM0 event

model:

1. By assigning the event handler script to an event-tag attribute

<input type=”button” id=”myButton” onclick = "alert('Mouse click!');" />

If the handler consists of more than a single statement, we can

use functions: <input type=”button” id=”myButton” onclick = "myHandler();"/>

2. Assign the address of the handler function to the event property

of the JavaScript object associated with the HTML element.

document.getElementById(!myForm!).onclick =

myHandler;

- This registration must follow both the handler function and

the XHTML form

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 20

5.6 Handling Events from Button Elements (continued)

- The disadvantage of specifying handlers by assigning them to event properties is that there is no way to use parameters:

document.getElementById(“myButton”).onclick= myButtonHandler;

- The advantages of specifying handlers by assigning them to event properties are:

1. It is good to keep HTML and JavaScript separate

2. The handler could be changed during use

Page 6: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 21

5.5 Handling Events from Body Elements

- Events most often created by body elements are load and

unload

- The unload event is more useful: used to cleanup before a

document is unloaded, when the user goes to some new doc.

- Example: the load event - triggered when the loading of a

document is completed

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 22

<?xml version = "1.0" encoding = "utf-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml1-strict.dtd"><!-- load.html A document for load.js --><html xmlns = "http://www.w3.org/1999/xhtml"><head><title> load.html </title><script type = "text/javascript" src = "load.js" ></script></head><body onload="load_greeting();"><p /></body></html>

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 23

function load_greeting () { alert("You are visiting the home page of \n" + "Pete's Pickled Peppers \n" + "WELCOME!!!");}

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 24

5.6 Handling Events from Button Elements

- Most commonly used event created by button actions is click.

- Plain Buttons – use the onclick property

- Radio buttons

- If the handler is registered in the markup, the particular button

that was clicked can be sent to the handler as a parameter, e.g.,

if planeChoice is the name of the handler and the value of a

button is 172, use onclick = !planeChoice(172)!

Page 7: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

<?xml version = "1.0" encoding = "utf-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- radio_click.hmtl A document for radio_click.js --><html xmlns = "http://www.w3.org/1999/xhtml">

<head><title> radio_click.html </title>

<script type = "text/javascript" src = "radio_click.js" ></script></head>

<body><h4> Cessna single-engine airplane descriptions </h4><form id = "myForm" action = ""><p>

<label><input type = "radio" name = "planeButton" value = "152" onclick = "planeChoice(152)" />Model 152 </label><br /><label> <input type = "radio" name = "planeButton" value = "172" onclick = "planeChoice(172)" />Model 172 (Skyhawk) </label><br /><label> <input type = "radio" name = "planeButton" value = "182" onclick = "planeChoice(182)" /> Model 182 (Skylane)</label><br /><label> <input type = "radio" name = "planeButton" value = "210" onclick = "planeChoice(210)" /> Model 210 (Centurian) </label></p>

</form></body></html>

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 25 Chapter 5 © 2010 by Addison Wesley Longman, Inc. 26

function planeChoice (plane) {// Produce an alert message about the chosen airplane switch (plane) { case 152: alert("A small two-place airplane for flight training"); break; case 172: alert("The smaller of two four-place airplanes"); break; case 182: alert("The larger of two four-place airplanes"); break; case 210: alert("A six-place high-performance airplane"); break; default: alert("Error in JavaScript function planeChoice"); break; }}

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 27 Chapter 5 © 2010 by Addison Wesley Longman, Inc. 28

5.6 Handling Events from Button Elements (continued)

- In the previous example, the specific button that was clicked is identified by the parameter sent in the handler call in the button element.

- An alternative to using the parameter would be to include code in the handler to determine which radio button was pressed (see following example).

Page 8: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

<!-- radio_click2.hmtl A document for radio_click2.js --><html xmlns = "http://www.w3.org/1999/xhtml">

<head><title> radio_click2.html </title><!-- Script for the event handler -->

<script type = "text/javascript" src = "radio_click2.js" ></script></head><body><h4> Cessna single-engine airplane descriptions </h4>

<form id = "myForm" action = ""><p><label><input type = "radio" name = "planeButton" value = "152" /> Model 152 <label><br />

<label><input type = "radio" name = "planeButton" value = "172" /> Model 172 (Skyhawk) </label><br />

<label><input type = "radio" name = "planeButton" value = "182" /> Model 182 (Skylane) </label><br />

<label><input type = "radio" name = "planeButton" value = "210" /> Model 210 (Centurian) </label></p></form>

<!-- Script for registering the event handlers -->

<script type = "text/javascript" src = "radio_click2r.js" ></script>

</body></html>

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 29

// radio_click2.js

function planeChoice (plane) {// Put the DOM address of the elements array in a local variable var dom = document.getElementById("myForm");

// Determine which button was pressed for (var index = 0; index < dom.planeButton.length; index++) { if (dom.planeButton[index].checked) { plane = dom.planeButton[index].value; break; }}

switch (plane) { case "152": alert("A small two-place airplane for flight training"); break; case "172": alert("The smaller of two four-place airplanes"); break; case "182": alert("The larger of two four-place airplanes"); break; case "210": alert("A six-place high-performance airplane"); break; default: alert("Error in JavaScript function planeChoice"); break; }}

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 30

// radio_click2r.js// The event registering code for radio_click2

var dom = document.getElementById("myForm");dom.elements[0].onclick = planeChoice;dom.elements[1].onclick = planeChoice;dom.elements[2].onclick = planeChoice;dom.elements[3].onclick = planeChoice;

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 31 Chapter 5 © 2010 by Addison Wesley Longman, Inc. 32

5.7 Handling Events from Textbox and Password Elements

- Text boxes and passwords can create 4 different events: blur, focus, change, select

- The Focus Event example:

- An event handler that blurs the text box every time the user

attempts to put it in focus

Page 9: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

...

<head>...

<script type = "text/javascript" src = "nochange.js" ></script></head>

<body><form action = ""><h3> Coffee Order Form </h3>

<table border = "border"><tr><th> Product Name </th><th> Price </th><th> Quantity </th></tr>

<tr><th> French Vanilla (1 lb.) </th><td> $3.49 </td>

<td><input type = "text" id = "french" size ="2" /></td></tr><tr><th> Hazlenut Cream (1 lb.) </th><td> $3.95 </td>

<td><input type = "text" id = "hazlenut" size = "2" /></td></tr><tr><th> Columbian (1 lb.) </th><td> $4.59 </td>

<td><input type = "text" id = "columbian" size = "2" /></td></tr></table>

<p><input type = "button" value = "Total Cost" onclick = "computeCost();" /><input type = "text" size = "5" id = "cost" onfocus = "this.blur();" /></p>

<p>

<input type = "submit" value = "Submit Order" />

<input type = "reset" value = "Clear Order Form" />

</p>

</form></body> </html>

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 33

// Nochange.js// This script illustrates using the focus event// to prevent the user from changing a text field

// The event handler function to compute the cost

function computeCost() {

var french = document.getElementById("french").value; var hazlenut = document.getElementById("hazlenut").value; var columbian = document.getElementById("columbian").value;

document.getElementById("cost").value = totalCost = french * 3.49 + hazlenut * 3.95 + columbian * 4.59;}

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 34

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 35

5.7 Handling Events from Textbox and Password Elements (continued)

- Checking Form Input: A good use of JavaScript, because it finds errors in form input before it is sent to the server for processing - So, it saves both: 1. Server time, and 2. Internet time - Things that must be done:

1. Detect the error and produce an alert message

2. Select the element (the select function)

- The select function highlights the text in the element

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 36

5.7 Handling Events from Textbox and Password Elements (continued)

- To keep the form active after the event handler is finished, the handler must return false

- This instructs the browser not to perform any default actions of

the event (e.g. not to submit the form data to the server for

processing, when the event is a click on the Submit button).

Page 10: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 37

5.7 Handling Events from Textbox and Password Elements

- Example – comparing passwords - The form has two password input boxes to get the passwords and Reset and Submit buttons - The event handler is triggered by the Submit button

- Handler actions:

1. If no password has been typed in the first box, focus on

that box and return false

2. If the two passwords are not the same, focus and select

the first box and return false if they are the same, return

true

<head><script type = "text/javascript" src = "pswd_chk.js" ></script></head><body><h3> Password Input </h3>

<form id = "myForm" action = "" ><p><label> Your password <input type = "password" id = "initial" size = "10" /></label><br /><br /><label> Verify password <input type = "password" id = "second" size = "10" /></label><br /><br />

<input type = "reset" name = "reset" /><input type = "submit" name = "submit" /></p></form>

<!-- Script for registering the event handlers --> <script type = "text/javascript" > document.getElementById("second").onblur = chkPasswords; document.getElementById("myForm").onsubmit = chkPasswords; </script>

<!-- <script type = "text/javascript" src = "pswd_chkr.js"> </script> --></body></html>

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 38

// pswd_chkr.js// Register the event handlers for pswd_chk.html

document.getElementById("second").onblur = chkPasswords;document.getElementById("myForm").onsubmit = chkPasswords;

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 39

// pswd_chk.js// An example of input password checking, using the submit // event // The event handler function for password checking

function chkPasswords() { var init = document.getElementById("initial"); var sec = document.getElementById("second"); if (init.value == "") { alert("You did not enter a password \n" + "Please enter one now"); init.focus(); return false; } if (init.value != sec.value) { alert("The two passwords you entered are not the same \n" + "Please re-enter both now"); init.focus(); init.select(); return false; } else return true;}

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 40

Page 11: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 41

- Another Example – Checking the format of a name and phone number

- The event handler will be triggered by the change event of

the text boxes for the name and phone number - If an error is found in either, an alert message is

produced and both focus and select are called on the

text box element

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 42

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 43

// validatorr.js// Register the event handlers for validator.html

document.getElementById("custName").onchange = chkName;document.getElementById("phone").onchange = chkPhone;

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 44

validator.js

Page 12: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 45

validator.js (ctd)

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 46

5.8 The DOM 2 Event Model

- DOM2 does not include DOM 0 features, but the DOM0 features will be supported by browsers in the foreseeable future

- DOM 2 is modularized: one module is Events, which has two submodules, HTMLEvents and MouseEvents, whose interfaces are Event (blur, change, etc.) and MouseEvent (click, mouseup, etc.)

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 47

- Event propagation

- The node of the document tree where the event is created is called the target node

- The capturing phase (the first phase) - Events begin at the root and move toward the target node - Registered and enabled event handlers at nodes along the way are run

- The target-node phase (second phase) - If there are registered but not enabled handlers there for the event, they are run

- The third phase is the bubbling phase - Event goes back to the root; all encountered registered but not enabled handlers are run

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 48

5.8 The DOM 2 Event Model (continued)

- Not all events bubble (e.g., load and unload)

- Any handler can stop further event propagation by calling the stopPropagation method of the Event object

- DOM 2 model uses the Event object method, preventDefault, to stop default operations, such as submission of a form, if an error has been detected

- Event handler registration is done with the addEventListener method

- Three parameters: 1. Name of the event, as a string literal 2. The handler function 3. A Boolean value that specifies whether the event is enabled during the capturing phase

node.addEventListener( "change", chkName, false);

Page 13: JavaScript - Computer Scienceepl425/notes/slides10-JavascriptXHTML-Sebesta… · Chapter 5 © 2010 by Addison Wesley Longman, Inc. 1 JavaScript !"# "$%&’" XHTML 2 Client-side JavaScript

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 49

5.8 The DOM 2 Event Model (continued)

- A temporary handler can be created by registering it and then unregistering it with removeEventListener

- The currentTarget property of Event always references the object on which the handler is being executed

- The MouseEvent interface (a subinterface of Event) has two properties, clientX and clientY, that have the x and y coordinates of the mouse cursor, relative to the upper left corner of the browser window

- An example: A revision of validator, using the DOM 2 event model

! SHOW validator2.html, validator2.js, & validator2r.js

- Note: DOM 0 and DOM 2 event handling can be mixed in a document

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 50

5.9 The navigator object

- Indicates which browser is being used

- Two useful properties

1. The appName property has the browser’s name

2. The appVersion property has the version #

- Microsoft has chosen to set the appVersion of IE8 to 4.0 (?)

- Firefox has chosen to set the appVersion of FX3 to 5.0 (?) and

the name to Netscape (?)

!SHOW navigate.html & navigate.js

Chapter 5 © 2010 by Addison Wesley Longman, Inc. 51

5.10 DOM Tree Traversal and Modification

- Traversal properties: parentNode, previousSibling,

nextSibling, firstChild, childNodes, and lastChild

- For example, if there is an unordered list with the id myList, the

number of list items in the list can be displayed with:

var dom = document.getElementById("myList");

var listItems = dom.childNodes.length;

document.write("Number of list items is: " +

listItems + "<br />");

- Modification methods: insertBefore,

replaceChild, removeChild, appendChild