5 - JS & Dom PDF
5 - JS & Dom PDF
Client-Side Processing –
Java Script and DOM
Week 5
Content of this Lecture
Core JavaScript
Object-oriented JavaScript
The Document Object Model (DOM)
JavaScript and Events
2
Client-Side
Basically, in a web-based system, the client deals with the view
and the controller in the MVC pattern; it can also engage in
model-based processing (when a “thick-client” approach is used)
The amount of processing to be done on the client has to be
carefully assessed
Usually, DOM (Document Object Model) is used to access and
update the XHTML document hosted by a browser
As such it can be manipulated using JavaScript , with the
language directly giving access to the DOM features
JavaScript allows us to program how the system will respond to
user-initiated (and other ) events, making use of event-handlers
This lecture revises material dealing with these issues
3
Java Script Refresher
Javascript – Some Advice
There are several JavaScript tutorials on the internet – for
example http://www.w3schools.com/JS/default.asp
There are several books available in the library
JavaScript Step by Step by Steve Suehring 2nd edition 2008 (416 pages)
{on-line}
Advanced JavaScript, Third Edition by Chuck Easttom 2008 {on-line}
5
JavaScript
Not really related to Java, except that like Java, it inherits a lot of
syntax and conventions from C.
JavaScript is object-based – it supports objects, essentially
supports classes, but does not have inheritance.
JavaScript was designed to be a client-side web scripting
language. JavaScript scripts (or programs) are interpreted by a
JavaScript interpreter running in a web browser.
A JavaScript program running in a browser knows about the
browser and the document(s) contained in it, as defined objects
that can be referenced, as variables with standard names, in any
script.
However, old browsers may not support the current version of the
language. 6
JavaScript
Within an HTML document, JavaScript code is contained within
“script” tags.
The JavaScript can be in-line, or the script tag can refer to an
external JavaScript file.
Generally we use separate files, although in some examples in
these notes we use in-line code for the purposes of easier
illustration of principles.
7
Syntax
Basically inherited from C, Java
Case-sensitive, e.g., pay attention to variable names
Semicolons are optional (but recommended) for ending
statements. We adopt a STANDARD that mandates them!
Comments – are as in Java
// single-line comment
/* line 1 comments, ...
line n comments */
8
Variables & Types
var myBook;
var myBook = “Beginning Ajax”;
myBook = “XML”;
Primitive datatypes for variables to indicate the kind of data hold
Number (including integer, double, etc.)
String
Boolean (true, false)
undefined (a declared non-reference variable that has not been given a
value has the undefined value)
null (an object reference variable has the value null when it does not refer
to any object)
Dynamic typing – the data type is determined at run time
(compare with Java or C or C++, where variables have to be
declared with a type (or class), and then the type is fixed)
myBook = 123; // data type changed from String to Number 9
Reference Datatypes
Contain a reference to the a place of memory that holds
the data
Object type is a reference type, e.g., array
function addFirst(a) {
a[0] = a[0] + 5;
}
var myArray = [10, 20, 30];
addFirst(myArray);
alert(“myArray is changed to ” + myArray);
10
Operators – as in C, Java
Assignment operator: =
Arithmetic operators: +, -, *, /, % (remainder)
Comparison operators
>, <, >=, <=, ==, !=
=== (equal and the same type)
!== (not equal or not the same type)
Logical operators: && (AND), || (OR), ! (NOT)
Increment and decrement operators: ++, --
11
Conditional Statements
if statement
if (condition) {statements}
if (condition 1) {
…
}
else if (condition 2) {
…
}
else {
…
}
switch statement
switch (myVar) {
case ‘value 1’: statements; break;
……
case ‘value n’: statements; break;
default: statements;
}
12
Loops
Four components
Initialisation
Test condition
Iterator (counter)
Loop body (optional break for jumping out and continue for getting into
next iteration immediately)
Three forms (for loop, while loop, do-while loop)
for (var a=2; a<1000; a=a*2) { document.write(“a = ”+ a + “<br>”); }
15
Object-oriented JavaScript
JavaScript is actually object-based, supporting a collection of
properties and methods for an object, but no inheritance
There are four types of objects
Built-in objects
Browser objects – these refer to objects associated with the
browser
Document objects – objects in the current document (see DOM)
User-defined objects
16
Object-oriented JavaScript
Why should we care about objects?
We shall see that JavaScript objects are a convenient way to
handle structured data sent from the server in the JSON format
We can bundle data structure and operations together, as in object-
oriented languages, helping us to structure programs
Document and browser objects are “objects”, and need to be
manipulated, so we need to understand the way to manipulate
objects in JavaScript.
In JavaScript, objects have properties (instance variables in Java)
and methods (as in Java)
They are accessed via the same “dot notation” as in Java
17
Example: Bank Account
properties and methods of BankAccount
properties methods
Account_number Deposit
Account_title Withdraw
Account_Balance Checkbalance
18
Built-in Objects
Constructor method: new
var myArray = new Array(); -- creates new array and assigns it to variable myArray
String
str.length, str.toUpperCase(), str.blink() -- length is a property; others are methods
http://www.w3schools.com/jsref/jsref_obj_string.asp
Date
Date(), d.getDate(), d.setYear(2006), d.toString()
http://www.w3schools.com/jsref/jsref_obj_date.asp
Math – a single object with many methods
Math.abs(x), Math.floor(y), Math.random()
http://www.w3schools.com/jsref/jsref_obj_math.asp
19
Built-in Object - Array
Defining an array
var myUnits=new Array();
var myUnits2=new Array(3);
var myUnits3=new Array("WAD", "Ajax", "XML");
Adding values
myUnits[0] = "WAA"; myUnits[1] = "WS";
http://www.w3schools.com/jsref/jsref_obj_array.asp
20
Browser and Document Objects
JavaScript only runs in a browser
When it runs, various objects relating to the browser that
JavaScript is running in, and the HTML document that
resides in the browser are automatically available, and
can be used in scripts
Using JavaScript commands, we can manipulate these
objects, and consequently update the interface that is
presented to the user; we can access browser windows,
documents resident in these windows, the browsing
history, and so on, thus allowing broad programmer
control over the user-interface
21
Browser Objects
Browser Object Model (BOM)
A collection of objects, that interact with the browser
window.
window: top level object in the BOM hierarchy
history: keep track of every page the user visits
location: contains the URL of the page
navigator: contains information about the browser name and
version
screen: provides information about display characteristics
document: belongs to both BOM and DOM
22
Window Object Properties (Part)
Property Description
closed Returns whether or not a window has been closed
document See Document object in DOM
history See History object
length Sets or returns the number of frames in the window
location See Location object
name Sets or returns the name of the window
opener Returns a reference to the window that created the window
outerheight Sets or returns the outer height of a window
pageXOffset Sets or returns the X position of the current page in relation to the
upper left corner of a window's display area
parent Returns the parent window
self Returns a reference to the current window
top Returns the topmost ancestor window
23
Window Object Methods (Part)
Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel
button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the contents of the current window
prompt() Displays a dialog box that prompts the user for input
setTimeout() Evaluates an expression after a specified number of milliseconds
24
History and Location Objects
History (wobj.history)
history.length; // the number of elements in the history list
history.back(); // loads the previous URL in the history list
history.forward() ; // loads the next URL in the history list
Location (wobj.location)
location.href; // sets or returns the entire URL
location.pathname; // sets or returns the path of the current URL
location.assign(url); // loads a new document
location.reload(); // reloads the current document
location.replace(url); // replaces the current document with a new one
25
User-Defined Objects
There are several ways to define objects in JavaScript
Using a “constructor” function, where objects are formed by
use of the keyword “new”. This way allows construction of
several similar objects, and so is in some sense like
defining a data type.
Using the “Object” constructor, and then assigning
properties and methods to the object. This way just the one
object is constructed, and this approach does not define a
data type.
Using an “object literal”
Using an object prototype (the way most similar to type or
class definition in other languages)
26
User-defined Objects using Constructor Function
var Car = function() {
this.wheels = 4; // specifies a property “wheels”
this.start = function() {
alert( "Vroom!");
}; // defines a method called “start”
};
var myVW = new Car();// declares a new Car object
myVW.start();
alert(myVW.wheels);
28
User-defined Objects using Object Constructor
We can also create a user-defined object with the Object() constructor
var member = new Object(); // this does NOT define a type, just a single
// object, and at this stage, there are no properties or methods
After this we can add properties
member.name = “Donald Duck”;
member.email = “dd@gmail.com”;
member.isRegistered = true;
and we can define methods, first just defining a separate function
function showMe() {alert(“I’m here!”);} // at this stage, not yet a method
30
User-defined Objects using Prototypes
Add new properties/methods
contrast this with Slides 27-
Every object is based on a prototype object 28, where we show an
function member (name, age) object defined using a
{ this.name = name; constructor function.
this.age = age;
}
member.prototype.present = function () {
alert(“I’m here!”);
}; // the method is defined and shared for all member objects
We can also use a prototype to specify a property with a default
value
member.prototype.isActive = true;
e.g. var person1= new member(“Peter”, 30);
person1.present();
alert(person1.name);
31
alert(person1.isActive);
Example – Creating and Using Objects
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN“
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Address Book</title>
<style type="text/css">
.ab {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: small;
color: #993300;
background-color: #CCFFCC; In this example we use embedded
padding: 5px; css and JavaScript for simplicity of
height: 100px; presentation only
width: 350px;
border: thin dotted #993300;
}
</style>
32
Example – Creating and Using Objects
<script type="text/javascript">
function addressBookItem (fname, lname, email) {
this.fname= fname;
this.lname = lname; Here we are defining
this.email = email; a “type” to represent
} a BookItem, which
stores 3 pieces of
addressBookItem.prototype.write = function() { data, and has a
var adrbook = "<p class='ab'>First Name: " + this.fname + "<br />"; method that writes
adrbook += "Last Name: " + this.lname + "<br />"; the data for the book
adrbook += "Email Address: " + this.email + "</p>"; into the browser
document.write(adrbook);
document.
}
</script>
33
Example – Creating and Using Objects
</head>
<body>
<script type="text/javascript">
var aB1 = new addressBookItem('Roger', 'Williams', 'rwilliams@gmail.com');
var aB2 = new addressBookItem ('Rose', 'Schultz', 'rose_s@earthlink.net');
aB1.write();
aB2.write();
</script>
</body>
</html>
34
When the HTML file is loaded ......
https://mercury.swin.edu.au/wlai/Lec5/example1.htm
35
The Document Object Model
(DOM)
Document Object Model (DOM)
W3C recommendation for advanced processing of both XML and
HTML/XHTML documents
http://www.w3.org/DOM/
39
DOM – The Key Concept
Input: An HTML(XHTML)/XML document
Internal representation: An in-memory "tree" data
structure that can be accessed by JavaScript
Access mode: A set of standard API calls
root
HTML/XML File
Internal representation
Processing
module DOM API
40
An HTML Tree
Note that the tags are fixed, but can
Root element: have styles applied
<html>
Element: Element:
<head> <body>
41
An XML Tree
Note that the tags are user-defined –
we’ll look at XML soon!!
42
DOM – Sample Code
43
DOM Interfaces
Everything in a document is a
node
The entire document is a Element Node
document node - document Type Type
Every HTML tag is an element Element 1
node
Attribute 2
The texts contained in the HTML
elements are text nodes Text 3
Every HTML attribute is an Comment 8
attribute node
Document 9
Comments are comment nodes
44
DOM Interfaces (Cont’d)
A Node Interface is used to read and write the individual
elements in the HTML (or XML) node tree.
The childNodes property of an element node (including the
documentElement) together with a loop construct can be used to
enumerate each individual node for processing.
Main functions of the DOM API
To traverse the node tree
To access and maybe change the nodes and their attribute values
To insert and delete nodes
45
Document Object Methods
createAttribute(attributeName) creates an attribute node
with the specified attribute name
createElement(tagName) creates an element with the
specified tagName
createTextNode(text) creates a text node, containing the
specified text
getElementsByTagName(tagName) returns a (node) list of
all nodes with the specified tag name
getElementsByName(name) returns a list of all nodes with
the specified name attribute
getElementById(id) returns the node with the specified id
attribute
46
Node Object Properties
attributes returns a NamedNodeMap containing all attributes for this node
childNodes returns a NodeList containing all the child nodes for this node
firstChild returns the first child node for this node.
lastChild returns the last child node for this node
nextSibling returns the next sibling node. Two nodes are siblings if they have the
same parent node
nodeName returns the nodeName, depending on the type
nodeType returns the nodeType as a number
nodeValue returns, or sets, the value of this node, depending on the type
parentNode returns the parent node for this node
previousSibling returns the previous sibling node. Two nodes are siblings if they
have the same parent node
47
Node Object Methods
appendChild(newChild) appends the node newChild at the end
of the child nodes for this node
cloneNode(boolean) returns an exact clone of this node. If the
boolean value is set to true, the cloned node contains all the
child nodes as well
hasChildNodes() returns true if this node has any child nodes
insertBefore(newNode,refNode) inserts a new node, newNode,
before the existing node, refNode
removeChild(nodeName) removes the specified node,
nodeName
replaceChild(newNode,oldNode) replaces the oldNode, with
the newNode
setAttributeNode(newAttr) insert the new attribute newAttr to
the node
48
Examples
document.getElementsByTagName(“myElement”)[0].parentNode
document.getElementById(“myId”).parentNode
document.getElementById(“myId”).childNodes[i]
document.getElementById(“myId”).childNodes.item(i)
document.getElementById(“myId”).firstChild
document.getElementById(“myId”).lastChild
document.getElementsByTagName(“myElement”)[0]
document.getElementsByTagName(“myElement”).item(0)
document.getElementsByTagName("myElement").item(
document.getElementsByTagName("myElement").childNodes.length - 1)
49
Adding New Element to an Existing Page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Adding New Elements</title>
<style type="text/css">
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: small;
font-weight: bold;
} In this example we use embedded
.newDiv { css and JavaScript for simplicity of
presentation only
background-color:#ffcccc;
}
</style>
https://mercury.swin.edu.au/wlai/Lec5/example2.htm 50
Adding New Element to an Existing Page (Cont’d)
<script type="text/javascript">
function newOne() {
var newEl = document.createElement('p');
var newTx = document.createTextNode('This is the new paragraph.'); newEl.appendChild(newTx);
var newPara =document.getElementById('newText'); newPara.appendChild(newEl);
}
function newColor() {
document.getElementById('newText').style.color="red";
}
</script>
</head>
<body><p>This is the first paragraph on the page.</p>
<div class="newDiv" id="newText"></div>
<p>This is the next paragraph on the original page.</p>
<form>
<input type="button" value="Add a new paragraph" onclick="newOne()" /><br /><br />
<input type="button" value="Make it red" onclick="newColor()" />
</form>
</body>
</html>
51
The innerHTML Property
function newOne() {
// create a new p element to hold the new paragraph text
var newEl = document.createElement('p');
// create a new text node with the text ‘This is the new paragraph’
var newTx = document.createTextNode('This is the new paragraph.');
// append the new text node to the new p element – ie, make it a child of the new p element
newEl.appendChild(newTx);
// get the (existing) document element that has id ‘newText’
var newPara =document.getElementById('newText');
//append the new p element to this
newPara.appendChild(newEl);
}
function newOne() {
var newPara =document.getElementById('newText');
newPara.innerHTML =“<p>This is the new paragraph.</p>”;
} // shorter, faster but not part of any standard 52
Java Script Event Model
JavaScript and Event Models
Events are necessary to create interaction between JavaScript
and HTML
Events occur when either a user (eg clicks a button) or the
browser does something (eg loads a page)
We have also seen the onReadyStateChange event for the XHR
object used in basic Ajax processing
We can bind an event to an event handler (or “call-back” function)
by using HTML attributes; the handler is the function that is called
automatically when the event occurs.
event handler 54
Attribute The event occurs when...
onabort Loading of an image is interrupted
onblur An element loses focus
onchange The user changes the content of a field
onclick Mouse clicks an object
ondblclick Mouse double-clicks an object
onerror An error occurs when loading a document or an image
onfocus An element gets focus
onkeydown A keyboard key is pressed
onkeypress A keyboard key is pressed or held down
onkeyup A keyboard key is released
onload A page or an image is finished loading
onmousedown A mouse button is pressed
onmousemove The mouse is moved
onmouseout The mouse is moved off an element
onmouseover The mouse is moved over an element
onmouseup A mouse button is released
onreset The reset button is clicked
onresize A window or frame is resized
onselect Text is selected
onsubmit The submit button is clicked
onunload The user exits the page
55
Event Models
Event bubbling: an event fires from the most-specific
target to the least-specific target.
mouseover fires child element (p) first
If there is no such event in the child, but one in the parent,
the parent event fires
Event capturing: an event fires from the least-specific
target to the most-specific target.
mouseover fires parent element (div) first
<div>
<p>Event order</p>
</div>
57
Event Registration - Example
This example displays a couple of paragraphs.
If you click on the FIRST paragraph, the background color changes, and a border
appears round the paragraph.
If you click on the button, the paragraph changes back to its original state, and the
click functionality is removed.
This is achieved by
• attaching an event-handler to the click event for the first paragraph,
which causes the background and border change
https://mercury.swin.edu.au/wlai/Lec5/example3.htm
58
Event Registration - Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Event Registration</title>
<script type="text/javascript"> In this example we use
embedded CSS and JavaScript
function addHandler () {
for simplicity of presentation
var addH = document.getElementById('p1'); only
if (addH.addEventListener) {
addH.addEventListener('click', addBord, false); Here we need code to handle
} browser event-model
else if (addH.attachEvent) { // IE8 & earlier versions differences – we ‘ask’ if a
addH.attachEvent('click', addBord); particular “add event” method
} exists, and if it does, this
} identifies the browser and we
call the method.
59
Event Registration - Example
function detHandler () {
var detH = document.getElementById('p1');
detH.style.border = ";
detH.style.backgroundColor = '#ffffff';
if (detH.removeEventListener) {
detH.removeEventListener('click', addBord, false);
}
else if (detH.detachEvent) { // IE8 & earlier versions
detH.detachEvent('click', addBord);
}
}
function addBord () {
var add = document.getElementById('p1');
add.style.border = '1px dotted #ff0000';
add.style.backgroundColor = '#ffff99';
}
</script>
</head>
60
Event Registration - Example
<body onload="addHandler()">
<p id='p1'>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed scelerisque
odio non ligula. </p>
<p>Integer mollis, libero et facilisis hendrerit, tellus dui porttitor quam, vitae iaculis nisi
mauris ac dui. Vivamus volutpat sollicitudin est. </p>
<form>
<input type='button' value='No border, please!' onclick='detHandler()'>
</form>
</body>
</html>
61
Event Registration - Example
function detHandler () {
var detH = document.getElementById('p1');
detH.style.border = ";
detH.style.backgroundColor = '#ffffff';
if (detH.removeEventListener) {
detH.removeEventListener('click', addBord, false);
}
else if (detH.detachEvent) { // IE8 & earlier versions
detH.detachEvent('click', addBord);
} function addBord (e) {
} var add = e.target;
function addBord () { add.style.border = '1px dotted #ff0000';
var add = document.getElementById('p1'); add.style.backgroundColor = '#ffff99';
add.style.border = '1px dotted #ff0000'; }
add.style.backgroundColor = '#ffff99';
}
</script>
</head>
62
https://www.w3schools.com/jsref/event_target.asp
Get the element that triggered a specific event.
e.g.
function hide (e) {
var t = e.target || e.srcElement; // IE8 & earlier versions
t.style.visibility = ‘hidden’;
}
63