JavaScript

Session 6 – JavaScript (Part 2)
Session 6
JavaScript
Part 2
W3C DOM Reading and Reference
T Background and introduction
http://www.w3schools.com/js/js_htmldom.asp
https://developer.mozilla.org/enUS/docs/DOM/DOM_Reference/Introduction
T Reference:
S JavaScript DOM properties – Flanagan book
S HTML5 binding to JavaScript
http://krook.org/jsdom/
Not 100% complete
S DOM Reference
developer.mozilla.org/en-US/docs/DOM/DOM_Reference
Use the HTML Interfaces
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
2
1
Session 6 – JavaScript (Part 2)
Learning Goals
T Understand the Document Object Model
T Understand how to perform client side form
validation
T Understand JavaScript event model
© Robert Kelly, 2001-2015
3
Access to the Document
T JavaScript begins to be useful when you can access
and modify the html in the document
“DOM” can mean different things
T Approaches
S Legacy DOM (Document Object Model) – Defined by
Netscape in the early days of the WWW
S IE 4 DOM – still in use, although Microsoft now supports
W3C DOM
S W3C DOM (level 3)
R well supported on modern browsers
R Includes the legacy DOM (known as Level 0 DOM)
S W3C DOM (level 4)
You may see the use of many of the
supported DOMs in current code
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
4
2
Session 6 – JavaScript (Part 2)
What is DOM?
T Document Object Model
T Convention for representing and interacting
with objects (HTML, XHTML and XML)
T Cross platform
T Binding with various languages
T Implemented as an API in JavaScript
© Robert Kelly, 2001-2015
5
Legacy DOM
T Does not take full advantage of the tree structure
of html documents
T Tends to reference html elements as members of
an array, for example images[], links[] and
forms[]
<form name=“f1”>
T Naming
S document.forms[0]
S document.forms.f1
S document.forms[“f1”]
Assuming the order of
elements in an html
document can cause
maintenance problems
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
6
3
Session 6 – JavaScript (Part 2)
W3C DOM
T Defines
S a standard set of objects (object tree) for an html
document
S Set of methods (language independent) to access the
html object
T Your Java and JavaScript (and other) programs can
S
S
S
S
Access a given node (element)
Walk the tree
Search for particular nodes or data (e.g., img tags)
Modify the nodes and insert sub-trees
Current version is DOM Level 3
(Level 4 in development)
© Robert Kelly, 2001-2015
7
DOM Access to html
This should clarify
the tag vs. element
discussion
Note that the root of the
html document is not
the same as the root
element
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
8
4
Session 6 – JavaScript (Part 2)
Node Object
T HTML elements are of type
Node/Element/HTMLElement
(inheritance hierarchy)
T You can get a handle to a node, and modify its
appearance
T Methods of Document can return
S An Element object (e.g., getElementById)
S A NodeList object (e.g., getElementsByTagName)
Notice whether the method uses singular or plural
9
© Robert Kelly, 2001-2015
Example – Changing Styles
T An easy way to change the appearance of an
element is to change its class attribute
“class” is a reserved
...
name in JavaScript, so
<style type="text/css">
the class property is
.blue {color:blue;}
.red {color:red;}
“className”
</style>
<script>
function change() {
var y = document.getElementById("X4");
y.className="red"; }
HTMLElement is a subclass of Element
</script>
...
<p id="X4" class="blue">Hello World</p>
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
10
5
Session 6 – JavaScript (Part 2)
Example – Hello DOM
T Illustrates
S Response to an event
S Modification of the style
property of a node
T Actions
S Obtain a handle
to an html element
S Modify the html
element
© Robert Kelly, 2001-2015
11
Html – Hello DOM Example
<head>
y is a Node object (not an array)
...
<script>
function change() {
Attributes are
var y = document.getElementById("X1");
usually set as
y.style.color="red"; }
properties
</script>
</head>
Level 2 CSS2Properties object
<body style="color:blue;">
<form method=“get" action=“HelloDOM“ >
<h2 id="X1" style="color:blue;">Hello World</h2>
<input type="button" onclick="change()"
value="Change appearance" name="cb" />
</form>
</body>
Clicking the button invokes the change() function
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
12
6
Session 6 – JavaScript (Part 2)
CSS2Properties Object
T Convenience mechanism
T The style property of the Node object is of type
CSS2Properties
p.style.color="red"; }
T The CSS2Properties object refers to the inline styles of
the element (not from the style sheet)
T Property values are strings
T Units are required
T Property names are similar to CSS property names,
except where it interferes with JavaScript naming (e.g.,
font-family => fontFamily)
© Robert Kelly, 2001-2015
13
Example
T Illustrates access to an array of elements
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
14
7
Session 6 – JavaScript (Part 2)
Example – Access Elements By Name
<head>
Notice that p is
...
accessed as an array
<script>
in this example
function change() {
var y = document.getElementsByTagName(“p");
y[0].style.color="red"; }
</script> </head>
<body style="color:blue;">
<form method="get" action=“HelloDOM“ >
<p id="X1" style="color:blue;">Hello World</p>
<p><input type="button" onclick="change()“
value="Change appearance" name="cb" /></p>
</form>
</body>
The HTMLDocument object also supports
DOM-HelloNodeArray.html
a
getElementsByName method
© Robert Kelly, 2001-2015
15
Example – Changing Element Contents
function change() {
var y = document.getElementById("X3");
y.innerHTML="Hello Text";
}
innerHTML is an
element property that
corresponds to all the
markup and content
within the element
Setting an innerHTML
property parses html
text into the html tree
DOM-HelloText.html
innerHTML is a useful relic of
older DOM specs
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
16
8
Session 6 – JavaScript (Part 2)
Example – Insert a Sub-Tree
T Instantiate a sub-tree
T Manipulate the sub-tree
T Insert into the HTML tree
17
© Robert Kelly, 2001-2015
“Pure” DOM HTML Change
T DOM provides methods to delete, create, clone,
and insert branches within the DOM tree
function change() {
var y = document.getElementById("X6");
var text = document.createTextNode(“ DOM text");
y.appendChild(text);
}
p
...
<p id="X6" class="blue">
Hello World</p>
Hello world
DOM text
DOM-HelloDOMText.html
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
18
9
Session 6 – JavaScript (Part 2)
How Many Nodes are in the Example?
<html>
html
<head>
<meta charset=“UTF-8" />
body
<title>Hello DOM</title>
head
<script>
...
meta
script
</script>
</head>
title
<body style="color:blue;">
form
<form method="get"
action=“HelloDOM“ >
h2
input
<h2 id="X1" style="color:blue;">
There are <span id="counter">
no count yet </span> Nodes</h2>
span
<input type="button"
onclick="countNodes()"
value="Count Nodes" name="cb" />
</form>
</body>
HelloDOMCounter.html
</html>
19
© Robert Kelly, 2001-2015
Let’s Count the Nodes
A span element,
enclosing the count
<script>
var numNodes=0;
function countNodes() {
var p = document;
h=p.getElementsByTagName("html");
nextLevel(h[0]);
meta
cc = document.getElementById("counter");
cc.innerHTML=numNodes;
}
function nextLevel(n) {
numNodes=numNodes+1;
if (n.hasChildNodes()) {
var children=n.childNodes;
for(var i = 0; i<children.length ; i++) {
nextLevel(children[i]);
}
}
return;
}
</script>
html
body
head
script
title
Why?
form
h2
input
span
Implicit declaration not
quite the same as explicit
HelloDOMCounter.html
2/23/2015
© Robert Kelly, 2001-2015
© Robert Kelly, 2001-2015
20
10
Session 6 – JavaScript (Part 2)
Text Nodes
T Text Nodes
html
S Title node contains text
(“Hello DOM”)
T White Space Text Nodes
body
head
meta
S Head node has more
children when you count
white space nodes
script
title
...
Hello DOM
© Robert Kelly, 2001-2015
21
Are We on Track?
T In your project html
S Count the number of hidden
form fields (input elements with
type=“hidden”)
S Count total input elements
S Display the result in an alert box
Hint: attributes is a property of
Node of type NamedNodeMap,
accessed as in:
Node.attributes.type.value
For hidden form fields the above
expression will evaluate to
“hidden”
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
22
11
Session 6 – JavaScript (Part 2)
Were We on Track?
function countFields() {
var p = document;
var hidden=0;
var h=p.getElementsByTagName("input");
for (var i = 0; i<h.length ; i++) {
if (h[i].hasAttributes()) {
if(h[i].attributes.type.value == "hidden") hidden++;
}
}
alert("hidden form fields: " + hidden + "/" + h.length);
}
<input type="button" onclick="countFields();"
value="Count Fields" />
© Robert Kelly, 2001-2015
23
Form Processing
T You can validate your form data in JavaScript
with a function invoked by the onsubmit event
T If your form handler function returns false, the
form data is not sent to the server
<form name=“z” onsubmit=“return isValid(...)” >
<input name=“zipcode” ... >
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
24
12
Session 6 – JavaScript (Part 2)
Prepare for the next HW
T Review the way the IBM site does validation
© Robert Kelly, 2001-2015
25
Cautions
T JavaScript is case sensitive
S maxlength html attribute of input element is accessed as the
maxLength property of JavaScript input element
T JavaScript keyword issues
S class attribute is accessed as className
S for attribute of label element is accessed as htmlFor property
T DOM is modularized so that not all DOM modules may
be implemented on a browser
T Binding of DOM to JavaScript differs from the binding
to Java
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
26
13
Session 6 – JavaScript (Part 2)
Have You Satisfied the Learning Goals?
T Understand the Document Object Model
T Understand how to perform client side form
validation
T Understand JavaScript event model
© Robert Kelly, 2001-2015
2/23/2015
© Robert Kelly, 2001-2015
27
14