0% found this document useful (0 votes)
27 views24 pages

Misy233 CH5

algorithme and programming notes

Uploaded by

christbiese11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views24 pages

Misy233 CH5

algorithme and programming notes

Uploaded by

christbiese11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

MISY233

CHAPTER 5
5.1 JavaScript Execution Environment
(JavaScript XHTML Documents)

• The JavaScript Window object represents the window in which the browser
displays documents
• The Window object provides the largest enclosing referencing environment
for scripts (Multiple windows possible but this course deals with single-
window Works)
• All global variables are properties of Window
• Implicitly defined Window properties:
• Document (XHTML): 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 arrays of anchors, links, images, applets. This
chapter deals with Form Array only
5.2 The Document Object Model (by W3C)

• 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)
• HTML5 was released in 2014
• DOM 4 was released in 2015
• The DOM is an abstract model that defines the interface between HTML documents
and application programs—an API
• Documents in the DOM have a treelike 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
Example : <input type = "text" name = "address">
would be represented as an object with two properties, type and name, with the values "text"
and "address"
5.2 The Document Object Model (cont.)

• 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
• DeveloperTools feature of browsers (F12 in FF displays DOM-Inspector)
• ‘DOM-Inspector’ is not enabled by default. To Enable it, F12 -> · · · -> Settings -> Enable-DOM

<html> <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>
5.3 Element Access in JavaScript

• There are several ways to do it


• Example (a document with just one form andone widget):

<form action = ""> <input type = "button«


name = "pushMe" />
</form>
1. DOM address
document.forms[0].element[0]

Problem: document changes


Solution : Use Element Names

2. 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: Name Attribute is not allowed in HTML 1.1 and old browsers
5.3 Element Access in JavaScript (cont.)

3. getElementById Method (defined in DOM 1)


Example:
<form action = "">
<input type = "button"id = "pushMe" />
</form>
document.getElementById("pushMe")

-Checkboxes and radio button have an implicit array, which has their name

<form id = "topGroup">
<input type = "checkbox"name = "toppings" value = "olives"/>
...
<input type = "checkbox"name = "toppings" value = "tomatoes"/>
</form>
...
let numChecked = 0;
let dom = document.getElementById("topGroup");
for (index = 0; index < dom.toppings.length; index++)
if (dom.toppings[index].checked]
numChecked++;
5.4 Events and Event Handling
• Purpose of Events: Requiring compulsary data in fields before submitting form
• An event is a notification that something specific has occurred, either with the
browser or an action of the browser user
• 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
• Don’t use document.write in an event handler, because the output may go on top
of the display. Events usually occur after the whole document is displayed.
EVENT TAG ATTRIBUTE EVENT TAG ATTRIBUTE
blur onblur mousedown onmousedown
change onchange mousemove onmousemove
Only a few events
click onclick mouseout onmouseout
dblclick ondblclick mouseover onmouseover
will be discussed
focus onfocus mouseup onmouseup in this course.
keydown onkeydown reset onreset
keypress onkeypress select onselect
keyup onkeyup submit onsubmit
load onload unload onunload
5.4 Events and Event Handling (cont.)

The same attribute can appear in several different tags


e.g., The onclick attribute can be in <a> anchor tag and <input>
field.

A text element gets focus in three ways:


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

Event handlers can be registered in 2 ways: (event tag attribute OR event property)
1. By assigning the event handler script to an event tag attribute
Registering
event handler to
onclick = "alert('Mouse click!');"
‘’form <input>’’
onclick = "myHandler();"
5.5 Handling Events from Body Elements

• Example: the load event -triggered when the loading of a document is


completed
5.6 Handling Events from Button Elements

• 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 planeChoiceis the name of the handler and the value of a button is 172, use
onclick = ″planeChoice(172)″
• This is another way of choosing the clicked button
5.6 Handling Events from Button Elements

• 2. (second way to register an event handler)


• Assign the address of the handler function to the event property of the JavaScript
object associated with the HTML element.

let dom =document.getElementById(″myForm″)


dom.elements[0].onclick = planeChoice;

• This registration must follow both the handler function and the HTML form
• If this is done for a radio button group, each element
of the array must be assigned
• In this case, the checked property of a radio button object is used to determine
whether a button is clicked
5.6 Handling Events from Button Elements (cont.)

• If the name of the buttons is planeButton

let dom = document.getElementById(″myForm″);


for (let index = 0;
index < dom.planeButton.length; index++) {
if (dom.planeButton[index].checked) {
plane = dom.planeButton[index].value;
break;
} }

• The disadvantage of specifying handlers by assigning them to event properties is


that there is no way to use parameters
• 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
5.7 Handling Events from Textbox and
Password Elements

• There are 4 events : Blur, Focus, Change, Select


• The Focus Event
• Can be used to detect illicit changes to a text box by blurring the element every time the
element acquires focus
• 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 server resources
• 2. Internet time
• Things that must be done by Script:
• 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
5.7 Handling Events from Textbox and
Password Elements (cont.)

• To keep the form active after the event handler is finished, the
handler must return false
Example : comparing passwords
• 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
• 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
5.7 Handling Events from Textbox and
Password Elements (cont.)

• 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
5.8 The DOM 2 Event Model

• Does not include DOM 0 features, but they are still supported by browsers
• 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.)
• Event propagation (This is a very complex model. Only basics will be covered)
• The node of the document tree where the event is created is called the target node,
and 3 phases are created ;
• 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 second phase is at the target node
• 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
5.8 The DOM 2 Event Model (cont.)

• 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. There are 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);
5.8 The DOM 2 Event Model (cont.)

• 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
• Note: DOM 0 and DOM 2 event handling can be mixed in a document
5.9 The navigator object

• Indicates which browser is being used


• Two useful properties
• 1. The appNameproperty has the browser’s name
• 2. The appVersionproperty has the version #
• Microsoft has chosen to set the appVersionof IE8 to 4.0 (?)
• Firefox has chosen to set the appVersionof FX3 to 5.0 (?) and the
name to Netscape (?)
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:

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


let listItems= dom.childNodes.length;
document.write("Number of list items is: " +
listItems+ "<br/>");

• Modification methods:insertBefore, replaceChild, removeChild, appendChild


The HTML DOM (Document Object Model)

<!DOCTYPEhtml>
<html>
<body>
<h2>APagewithHTMLDOM</h2>
<pid="demo"></p>
<script>

document.getElementById("demo").innerHTML="HelloWorld!";
</script>
</body>
</html>
method property
Finding HTML Elements by Id

<!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements by Id</h2>
<p id="intro">HelloWorld!</p>
<p>This example demonstrates the get Elements By Id
method.</p>
<p id="demo"></p>
<script>
letmyElement=document.getElementById("intro");
document.getElementById("demo").innerHTML=
"Thetextfromtheintroparagraphis"+myElement.innerHTML;
</script>
</body>
</html>
Finding HTML Elements by Tag Name

<!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements by Tag Name</h2>
<div id = "main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the get Elements By Tag Name method.</p>
</div>
<p id="demo"></p>
<script>
let x = document.getElementById("main");
let y = x.getElementsByTagName("p");
document.getElementById("demo").innerHTML=
'The first paragraph (index 0) inside "main" is:'+y[0].innerHTML;
</script>
</body>
</html>
Finding HTML Elements with Forms

<!DOCTYPEhtml>
<html>
<body>

<h2>Finding HTML Elements with forms</h2>


<form id="frm1" action="">
<input type="radio" name="age« value="10"/>10
<input type="radio" name="age" value="20"/>20
</form>
<script>
letx=document.getElementById("frm1");
for(leti=0;i<x.length;i++)
{ alert(x[i].value);
}
</script>
</body>

You might also like