0% found this document useful (0 votes)
37 views

Lect4 JS2

This document provides an overview of client-side JavaScript and the Document Object Model (DOM). It discusses how JavaScript allows scripts to interact with web pages and defines a hierarchical object model for accessing and manipulating page elements. The key topics covered include the JavaScript execution environment, the Window and Document objects, DOM navigation and manipulation, and different methods for accessing elements like forms, buttons, text boxes and selecting their associated JavaScript objects.

Uploaded by

precila
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Lect4 JS2

This document provides an overview of client-side JavaScript and the Document Object Model (DOM). It discusses how JavaScript allows scripts to interact with web pages and defines a hierarchical object model for accessing and manipulating page elements. The key topics covered include the JavaScript execution environment, the Window and Document objects, DOM navigation and manipulation, and different methods for accessing elements like forms, buttons, text boxes and selecting their associated JavaScript objects.

Uploaded by

precila
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Lecture 4.

JavaScript: Part 2

Introduction

Client-side JavaScript defines the collection of


objects, methods, and properties

They allow scripts to interact with XHTML documents


on the clients

Contents

Object hierarchy reflecting the structure of documents

Overview of the Document Object Model (DOM)

Accessing XHTML document elements in JavaScript

Events and event handling

JavaScript Execution Environment


A browser displays an XHTML document in a window on
the screen of the client

The JavaScript Window object

It represents the window that displays the document

Its properties are visible to all scripts in the windows


XHTML document (Ex) all global variables

It provides the largest enclosing referencing environment


for JavaScript scripts

There can be more than one Window object

Other Window properties

document: a reference to the Document object that


the window displays

The Document object represents the displayed XHTML


document

frames: an array of references to the [multiple] frames


of the window

Document object

forms array: each references to a form in the document

Each Forms array element has an elements array,


which has references to the forms elements such as
buttons and menus
Form elements are usually referenced by name, but this
is a problem for radio buttons

JavaScript objects associated with the elements in a


document can be addressed in several ways

Other property arrays are for anchors, links, images and


applets

Forms

A form is the usual way information is gotten from a


browser to a server
HTML has tags to create a collection of objects that
implement this information gathering
The objects are called widgets (e.g., radio buttons
and checkboxes)
When the Submit button of a form is clicked, the
forms values are sent to the server
All of the widgets, or components of a form are
defined in the content of a <form> tag
The only required attribute of <form> is action, which
specifies the URL of the application that is to be
called when the Submit button is click
If no action, the value of action is the empty string
7

<input> tag

specifies many of the commonly used controls


Ex) text,

passwords,
checkboxes,
radio buttons, and
the special buttons Submit and Reset

type attribute specifies the particular kind of control

type = text

Creates a horizontal box for text input

Default size is 20; it can be changed with the size attribute

If more characters are entered than will fit, the box is


scrolled (shifted) left

If you dont want to allow the user to type more characters


than will fit, set maxlength, which causes excess input to
be ignored
<input type = "text" name = "Phone" size = "12"
maxlength = "25" >

type = password

If the contents of a text box should not be displayed


when it is entered by the user.

Instead, asterisks are displayed by the browser


<input type = "password" name = "mypassword"
size = "12" maxlength = "10" >

10

type = checkbox

To collect multiple choice input

Every checkbox requires a value attribute, which is the


widgets value in the form data when the checkbox is
checked

A checkbox that is not checked contributes no value


to the query string

By default, no checkbox is initially checked

To initialize a checkbox to checked, the checked


attribute must be set to "checked"

11

Example
Grocery Checklist
<form action = ""> <p>
<input type = "checkbox" name = "groceries"
value = "milk" checked = "checked"> Milk <br/>
<input type = "checkbox" name = "groceries"
value = "bread"> Bread <br/>
<input type = "checkbox" name = "groceries"
value= "eggs"> Eggs
</p> </form>

12

type = radio

Collections of checkboxes in which only one button can be


checked at a time

Every button in a radio button group MUST have the same


name

If no button in a radio button group is pressed, the


browser often presses the first one

13

Example
Age Category
<form action = ""> <p>
<input type = "radio" name = "age"
value = "under20" checked = "checked"> 0-19 <br/>
<input type = "radio" name = "age"
value = "20-35"> 20-35 <br/>
<input type = "radio" name = "age"
value = "36-50"> 36-50 <br/>
<input type = "radio" name = "age"
value = "over50"> Over 50 </p>
</form>

14

<select> tag

If the number of possible choices is large, the displayed form


becomes too long to display

There are two kinds of menu

those that behave like checkboxes

those that behave like radio buttons (the default)

Menus that behave like checkboxes are specified by including the


multiple attribute, which must be set to "multiple"

The name attribute of <select> is required

The size attribute of <select> can be included to specify the


number of menu items to be displayed (the default is 1)

If size is set to 1 or if multiple is not specified, the menu is


displayed as a pop-up menu

15

Example
Grocery Menu - milk, bread, eggs, cheese
<form action = "">
<p>
With size = 1 (the default)
<select name = "groceries">

<option> milk </option>


<option> bread </option>
<option> eggs </option>

<option> cheese </option>


</select>
</p>

</form>
16

Example

17

<textarea> tag

Usually include the rows and cols attributes specify the


size of the text area

Default text can be included as the content of <textarea>

Scrolling is implicit if the area is overfilled

18

Example
Please provide your employment aspirations
<form action = "">
<p>
<textarea name = "aspirations" rows = "3 cols = "40">
(Be brief and concise)
</textarea>
</p>
</form>

19

Reset and Submit buttons

Both are created with <input>

<input type = "reset" value = "Reset Form">


<input type = "submit value = "Submit Form">

Submit has two actions:


1. Encode the data of the form
2. Request that the server execute the serverresident program specified as the value of the
action attribute of <form>

A Submit button is required in every form


20

Document Object Model (DOM)

Under development by w3c since the mid-90s


DOM 0 is supported by all JavaScript browsers
DOM 1 is the first W3C DOM spec. issued in Oct. 1998
DOM 2 is issued in Nov. 2000
Nearly completely supported by Firefox2 / IE6 does not.

The motivation is to provide a specification that would


make Java programs and JavaScript scripts that deal
with HTML documents portable among various browsers

The DOM is an application programming interface (API)


that defines the interface between HTML documents
and application programs

21

Document Object Model (DOM)

Actual DOM specification consists of a collection of


interfaces, including one for each document tree node
type.

These interfaces are similar to Java interfaces and C++


abstract classes.

With the DOM, users can write code in programming


languages to

create documents,

move around in their structures, and

change, add, or delete elements and their content.

22

Document Object Model

It is an OO model - document elements are objects


with both data and operations.

The data (operations) are called properties (methods).

A language that supports the DOM must have a binding


to the DOM constructs

Correspondence between constructs in the language and


elements in the DOM

In the JavaScript binding, HTML elements are represented


as objects and element attributes 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
23

Document and its DOM structure


<html>
Document
<head>
<title> A simple document </title>
</head>
<head>
<body>
<body>
<table>
<tr>
<table>
<title>
<th> Breakfast </th>
<td> 0 </td>
<tr>
<td> 1 </td>
A simple document <tr>
</tr>
<tr>
<th> <td> <td>
<th> <td> <td>
<th> Lunch </th>
<td> 1 </td>
<td> 0 </td>
</tr>
Breakfast 0 1
Lunch 1
0
</table>
</body>
</html>

24

Element Access in JavaScript

Elements of an XHTML document have corresponding


objects in an embedded JavaScript script

The addresses of these objects are required for

handling the events

making dynamic changes to documents.

There are several ways to address the object


associated with an XHTML form element
1. Using the forms and elements arrays in DOM 0
2. Using element names
3. Using getElementById JavaScript method in DOM 1

25

Element Access in JavaScript


1. In DOM 0 : Using the forms and elements arrays

DOM address: the address of JavaScript object


associated with an XHTML element
(Ex)

<html> <head></head>
<body>
<form action = "">
<input type = "button" name = "pushMe">
</form>
</body>
</html>

buttons DOM address:


var dom = document.forms[0].elements[0]

Problem: A change in the document could invalidate


this address such as addition of new button
26

Element Access in JavaScript


2. Using element names requires the element and all of
its ancestors (except body) to have name attributes

<body>
<form name = "myForm" action = "">
<input type = "button" name = turnIton>
</form>
</body>

(Ex) buttons DOM address: document.myForm.turnItOn

Problem: XHTML 1.1 standard does not allow form


elements to have name attribute
27

Element Access in JavaScript


3. Using getElementById JavaScript method

Defined in DOM 1

Using an elements unique identifier


Ex:

<form action = "">


<input type = "button" id = turnItOn">
</form>

document.getElementById(turnItOn")

Form elements often have both ids and names, both


set to the same value

ids for DOM addressing / names for form-processing


28

Alternative Element Access in JavaScript

An alternative to names and ids is to use the implicit


arrays associated with checkbox and radio button
group

Every such group has an array with the DOM


addresses of the individual buttons in the group

Its array name is same as the group name

These arrays are properties of the form in which the


buttons appear

29

Alternative Element Access in JavaScript


<form id = vehicleGroup">
<input type=checkbox" name=vehicles value=car /> Car
<input type=checkbox" name=vehicles value=truck /> Truck
<input type=checkbox" name=vehicles value=bike /> Bike
</form>

The implicit array, vehicles, has three elements


referencing the three objects for the three checkbox
elements
var numChecked = 0;
var dom=document.getElementById(vehicleGroup);
for (index=0; index<dom.vehicles.length; index++)
if (dom.vehicles[index].checked)
numChecked++;
30

Events and Event Handling

HTML 4.0 standard provided the first spec. of an event


model for documents, referred to as the DOM 0 event
model

Although limited in scope, it is supported by all


browsers that support JavaScript

A complete and comprehensive event model was


specified by DOM 2

31

Event-Driven Programming

A category of use of JavaScript for Web programming is


to detect certain activities of the browser and the user
and provide computation when these activities occur

The computations are specified using a event-driven


programming

In conventional programming, the code itself specifies


the order in which the code is executed

In event-driven programming, code is executed at


unpredictable times, often triggered by user interactions
with the executing program

32

Events and Event Handler

An event is a notification that something specific has


occurred, either
(i) with the browser such as page loading, or
(ii) by a user interaction like mouse click on a button

An event handler is a script executed on an event,


enabling web documents to be responsive to browser
and user activities

Similar to the exception handling of C++ or Java

Because events are JavaScript objects, their names are


case sensitive - all are in lowercase only

33

Event Registration

The process of connecting an event handler to an


event is called registration

Two registration approaches


assigns

tag attributes

assigns

handler addresses to object properties

JavaScript defines a collection of events.

Events are associated with XHTML tag attributes,


which connects the events to handlers.

The attribute names are closely related to their


associated events.

34

Events and Tag Attributes


Event
abort
blur
change
click
error
focus
load
mouseout
mouseover
reset
resize
select
submit
unload

Tag Attribute
onabort
onblur
onchange
onclick
onerror
onfocus
onload
onmouseout
onmouseover
onreset
onreszie
onselect
onsubmit
onload
35

Events and Event Handling

The same attribute can appear in several different tags


(Ex) The onclick attribute can be in <a> and <input>

A text element gets focus in three ways:


1. When the user puts the mouse cursor over it and
presses the left mouse button
2. When the user tabs to the element

3. By executing the focus method


Table 5.2: Event Attributes and Their Tags
36

Event Attribute and their Tags


Attribute

Tag

Description

onblur

<a>

The link loses the input focus

<button>

The button loses the input focus

<input>

The input element loses the input focus

<textarea> The text area loses the input focus

onchange

<select>

The selection element loses the input focus

<input>

The input element is changes and loses the


input focus

<textarea>

The text area is changed and loses the input


focus

<select>

The selection element is changed and loses


the input focus
37

Event Attributes and their Tags


Attribute

Tag

Description

onclick

<a>

The user clicks on the link

<input>

The input element is clicked

<a>

The link acquires the input focus

<input>

The input element receives the input focus

onfocus

<textarea> A text area receives the input focus


<select>
...

A selection element receives the input focus

...

38

Two Methods for Event Registration


1. By assigning the event handler script to an event
tag attribute
<input type = button name = myButton
onclick = alert(Mouse clicked!); />
2. By writing event handlers as functions
/* event handler as function */
/* when the handler has more than one statement */
<input type = button name = myButton
onclick = myButtonHandler();

39

Example: the load event

triggered when the body of the document has


been loaded
<!-- load.html
An example to illustrate the load events -->
<html> <head>
<title> The onLoad event handler> </title>
<script type = "text/javascript">
<!-function load_greeting () {
alert("You are visiting the home page of \n"
+ "Pete's Pickled Peppers \n"
+ "WELCOME!!!"); }
// -->
</script>
</head>
<body onload="load_greeting();"> </body>
</html>

Microsoft Internet Explorer

You are visiting the home page of


Petes Pickled Peppers
WELCOME!!!

OK

SHOW load.html

40

Handling Events From Button Elements

Plain Buttons
<input type = button name = freeOffer

id = freeButton />

Registration of a handler function

1. <input type = button name = freeOffer


id = freeButton
onclick = freeButtonHandler(); />
2. document.getElementById(freeButton).onclick =
freeButtonHandler;
41

Radio buttons
A simple and effective way to collect multiple-choice
input
<input type = "radio" name = "button_group"
value = "blue" onclick = "handler()">
Cant use the elements name to identify it, because
all buttons in the group have the same name

The checked property of a radio button object is true


if the button is pressed

42

Radio buttons
Must use the DOM address of the element
Ex) var rElement = document.myForm.elements;

Now we have the name of the array of elements of the


form

for (var index = 0; index < rElement.length;


index++)
{
if (rElement[index].checked) {
element = rElement[index].value;
break; }
}

SHOW radio_click.html
43

Event handlers
Event handlers can be specified by assigning them to
properties of the JavaScript objects associated with
the HTML elements

If the event handler is a function, just assign its name to


the property, as in
document.myForm.elements[0].onclick = myHandler;

This sets the handler for the first element in the form

This statement would need to follow both the handler


function and the HTML form specification.

44

Event Handlers

If this is done for a radio button group, each element of


the array must be assigned

SHOW radio_click2.html

45

Handler as Event Property


The disadvantage of specifying handlers by assigning
them to event properties is that there is no way to
use parameters
The advantages to registering handlers as properties
over registering them in XHTML attributes:
1. It is good to keep HTML and JavaScript separate

modularization of XHTML documents

cleaner in design, easier to maintain

2. The handler could be changed during use

register a different handler for the other event


46

Handling Events from Text Box

Text boxes and passwords can create four different


events:

blur

focus

change

select

47

Blur Event

Prevents a change to a text box whenever the user


attempts to put it in focus
(Ex) When JavaScript pre-computes the total cost of
an order and display it to the customer before
submission, the user might try to lower the price.

=> show nochange.html

48

Validating Form Input

Checking Form Input


checking the format
checking the completeness of form input

It finds errors in the form input before sending it to


the server for processing
-> results in less network traffic/quicker response time

Things that must be done:


1. Detect the error and produce an alert message

2. Put the element in focus (the focus function)


3. Select the element (the select function)
49

Validating Form Input

The focus function puts the element in focus, that is, it


puts the cursor in the element
document.getElementById("phone").focus();

The select function highlights the text in the element


document.getElementById("phone").select();

Neither select nor focus work with NS 6.2

50

Validating Form Input

If an event handler returns false, the browser does not


perform any default actions of the event.
(Ex) For the click event on the Submit button

The default action is to submit the form data to the


server

If an event handler validates the user input, and the


input is incorrect, the event should return false to avoid
sending the form data to the server

51

Example 1
To keep the form active after the event handler is
finished, have it return false

(Ex) comparing passwords

Typically, the user is asked to type in the password


twice, the second for the verification.

The program must verify that the second typing of the


password is the same as the first

The form just has two password input boxes to get the
passwords and Reset and Submit buttons

The event handler is triggered by the Submit button

52

Example 1

Handler actions:

If no password has been typed in the first box, alert it,


focus on that box and return false

If the two passwords are not the same, alert it, focus
and select the first box and return false if they are the
same, return true

53

Display of pswd_chk.html
Password Input
Your password
Verify password
Reset

Submit Query

Password Input

Your password

Microsoft Internet Explorer

Verify password
Reset

The two passwords you entered are not the same


Please re-enter both now

Submit Query
OK

-> SHOW pswd_chk.html


54

Example 2
(Ex) 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 any box, an alert message is


produced and both focus and select are called on the
text box element

Another event handler is used to produce a thank you


alert message when the input is ok

55

Figures
Customer Information
Heel, Ferris, W.

Name (last name, first name, middle initial)

999-555-333

Phone number (ddd-ddd-dddd)

Reset

Submit Query

Customer Information
Heel, Ferris, W.

Name (last name, first name, middle initial)

999-555-333

Phone number (ddd-ddd-dddd)

Reset

Submit Query

Microsoft Internet Explorer

The phone number you entered (999-555-333) is not in the correct form.
The correct form is: ddd-ddd-dddd
Please go back and fix your phone number

OK
56

Name Format

Last name, first name, middle initial, where


1. the first and last name begin with uppercase letters
and have at least one lowercase letter.
2. Both must be followed immediately by a comma and
possibly one space.
3. The middle initial is uppercase.
4. It may or may not be followed by a period

=> /^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z].?$/


SHOW validator.html

57

The DOM 2 Event Model

Does not include DOM 0 features, but they are still


supported

Much more powerful than the DOM 0 model

Microsoft does not support it, yet

Not all events bubble

Any handler can stop further propagation by calling


the stopPropagation method of the Event object

58

Event propagation

The node of the document tree where the event is


created is called the target node
The first phase is called the capturing phase
Events begin at the root and move toward the target
node

The second phase is at the target node

If there are registered event handlers at nodes along


the way (before the target node is reached), if one is
enabled, it is run
If there are registered handlers there for the event,
they are run

The third phase is the bubbling phase

Event goes back to the root; all encountered


registered handlers are run
59

The DOM 2 Event Model

DOM2 model uses the Event object method,


preventDefault to stop default operations, such as
submission of a form, even though an error has been
detected

Event handler registration is done with the


addEventListener method using 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);
60

The DOM 2 Event Model

A temporary handler can be created by registering it


and then unregistering it with remove EventListener

The currentTarget property of Event always references


the object on which the handler is being executed

The MouseEvent object (a subobject 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

61

The DOM 2 Event Model

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


event model
SHOW validator2.html

Note: DOM 0 and DOM 2 event handling can be mixed


in a document

62

The navigator object

Indicates which browser is being used

Two useful properties


1. The appName property has the browsers name
2. The appVersion property has the version #

Microsoft has chosen to set the appVersion of IE6 to 4


(?)

Netscape has chosen to set the appVersion of NS6 to


5.0 (?)

SHOW navigator.html & Figures 5.9 & 5.10


63

Figure 5.9 and 5.10


Alert

The browser is: Netscape


The version number is: 5.0 (Windows; en-US)

OK

Figure 5.9 For Netscape 6

Microsoft Internet Explorer

The browser is: Microsoft Internet Explorer


The version number is: 4.0 (compatible; MSIE 6.0; Windows NT 5.1; PeoplePC 1.0; ISP)

OK

Figure 5.10 For Internet Explorer 6

64

You might also like