Introduction to
JavaScript – Part IIIHamid Zarrabi-Zadeh
Web Programming – Fall 2013
Outline
• Document Object Model (DOM)
• The Browser Object Model
• Event Handling
• Exception Handling
2
Document Object Model
• The Document Object Model (DOM) defines a
standard for accessing documents through an
object model
• DOM is platform and language independent
• It allows programs and scripts to dynamically
access and update the content, structure, and
style of a document
3
The W3C DOM
• The W3C DOM standard is separated into three
different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
4
The HTML DOM
• The HTML DOM defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
5
The HTML DOM Tree
• The HTML DOM represents HTML document as a
tree of objects
6
Finding Elements
• Using get methods
getElementById
getElementsByName
getElementsByTagName
getElementsByClassName
• Using document object collections
anchors, forms, images, links
7
var x = document.getElementById('main');
var y = x.getElementsByTagName('p');
var form = document.forms[0];
Getting Information
• For each element, information can be obtained
from
nodeValue – The text of a text node
nodeName – The tag name
nodeType – The type of node (a number)
innerHTML – The inner HTML content
8
var x = document.getElementById('main');
alert(x.nodeName);
Updating Elements
• Change HTML content
element.innerHTML = new HTML
• Change an HTML attribute
element.attribute = new value
9
var x = document.getElementById('image');
x.src = 'sun.png'
x.title = 'The Sun!';
Changing Style
• We can change the style of an element using
the element's style object
element.style.property = new style
10
var x = document.getElementById('main');
x.style.color = 'blue';
x.style.backgroundColor = '#eee';
Navigating DOM Tree
• Navigation pointers
parentNode, firstChild, lastChild, childNodes, nextSibling,
previousSibling
• Root pointers
document.body
document
.documentElement
11
Add/Remove Elements
• Methods for adding/removing HTML elements
createElement
createTextNode
appendChild
removeChild
12
var p = document.createElement('p');
var node = document.createTextNode('Test');
p.appendChild(node);
var div = document.getElementById('main');
div.appendChild(p);
Event Handling
Assign Event Handlers
• Using HTML event attributes
<button onclick="change(this)">Try it</button>
• Using HTLM DOM events
14
var x = document.getElementById('button');
x.onclick = function() {
this.innerHTLM = Date();
}
Common Events
• Mouse Events
onclick, ondblclick, onmouseover, onmouseout
• Keyboard Events
onkeypress, onkeydown, onkeyup
• Frame Events
onload, ununload, onresize, onscroll
• Form Events
onfocus, onblur, onchange, onsubmit
15
Timing Events
• One-time events
setTimeout (func, milliseconds);
• Repeated Events
setInterval(func, milliseconds);
• Stop Execution
clearInterval(), clearTimeout()
16
var timer = setInterval(myTimer, 1000);
document.getElementById('stop-timer').onclick =
function() { clearInterval(timer); }
The Browser Object
Model
The Browser Object Model
• The window object represents the browser's
window.
• Global variables are properties of the window
object.
• Global functions are methods of the window
object.
• Even the document object (of the HTML DOM) is
a property of the window object
18
The Window Object
• Some properties
window.innerHeight - inner height of the browser window
window.innerWidth - inner width of the browser window
• Some methods
window.open() - open a new window
window.close() - close the current window
window.moveTo() - move the current window
window.resizeTo() - resize the current window
19
Window Location
• The window.location object can be used to get
the current page address (URL) and to redirect
the browser to a new page
• Location properties
location.href - the URL of the current page
location.hostname - the domain name of the web host
location.pathname - the path and filename
location.port - the port of the web host
location.protocol - the web protocol used
20
Window History
• The window.history object contains the history of
the window
• Useful methods
history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the
browser
21
<button onclick="history.back()">Back</button>
Exception Handling
Exception Handling
• JavaScript has try and catch keywords for
handling JavaScript errors
23
try {
runSomeCode();
} catch (e) {
alert(e.name + ': ' + e.message);
}
Raising Exceptions
• You can use throw keywords to raise an
exception
24
try {
a = 1 * str;
if (isNaN(a))
throw 'Not a number';
} catch(err) {
alert(err);
}
Error Object
• Runtime errors in JavaScript throw Error objects
• You use the generic Error constructor to throw
your own exceptions
25
try {
throw new Error('Oops!');
} catch (e) {
msg = e.name + ': ' + e.message+ '\n';
msg += e.fileName + ': '+ e.lineNumber;
alert(msg);
}
References
• W3Schools
http://www.w3schools.com/js
• JavaScript: The Good Parts
By Douglas Crockford
• A re-introduction to JavaScript
http://developer.mozilla.org/en-US/docs/Web/JavaScript
26