WDIM387 Week 4

Browsers, DOM, Events, and AJAX


Instructor: Dan Muzyka

danmuzyka.ai@gmail.com

Browser Object Model


In browsers, the window object is used as the JavaScript global object. 

var hansel = {
firstName: "Hansel",
age: 8,
favoriteFood: "gingerbread"
};
window.gretel = {
firstName: "Gretel",
age: 8,
favoriteFood: "jelly beans"
};
console.dir(window.hansel);
console.dir(gretel);

Browser Object Model

The document object represents the HTML document inside the window. It is a child of the window object.

console.log(window.document === document); // true


The document is comprised of nodes, which correspond with the HTML tags and text in the document. The root <html> element is represented by the documentElement property of document.

console.log(document.documentElement);

Document Object Model

A high-level representation of the document node tree looks something like this:

  • document
    • html (documentElement)
      • head
        • title
        • meta
        • link
      • body
        • div#content
          • p
          • p

Document Object Model

You can traverse the DOM tree using the childNodes and parentNode properties of a node.

console.dir(document.childNodes);
console.dir(document.body.childNodes);
console.log(document.body.parentNode);
console.log(document.body.childNodes[1].parentNode === document.body);

Other ways to traverse the DOM tree: firstChild, lastChild, nextSibling, previousSibling.

console.log(document.body.childNodes[1] === document.body.firstChild.nextSibling);

console.log(document.body.lastChild === document.body.childNodes[document.body.childNodes.length - 1]);

Document Object Model

Other node properties: nodeType. An integer representing the type of node. Important values are:

ELEMENT_NODE 1
TEXT_NODE 3
DOCUMENT_NODE 9
DOCUMENT_TYPE_NODE 10
DOCUMENT_FRAGMENT_NODE 11
console.log(document.nodeType);
console.log(document.body.nodeType);
console.log(document.documentElement.previousSibling.nodeType);

Document Object Model

Other node properties: nodeName. A string, either the name of the tag in all caps (if the node is an element node), or '#text' for a text node, or '#document' for the document node.

console.log(document.nodeName); // #document
console.log(document.body.nodeName); // BODY
console.log(document.head.childNodes[0].nodeName); // #text

Document Object Model

Other node properties: nodeValue. For text nodes, the value of the text. For most other node types, null.

Document Object Model

You can access more specific DOM nodes directly.

var contentDiv = document.getElementById('content'),
paragraphs = contentDiv.getElementsByTagName('p'),
firstLink = paragraphs.querySelector('a'), // querySelector and
// querySelectorAll work
allLinks = paragraphs.querySelectorAll('a'); // on modern browsers,
// including IE 8+

Document Object Model

DOM methods are expensive, so a good pattern is to use them as little as possible by storing the results in a variable.

// antipattern
for (var i = 0; i < 100; i += 1) {
    document.getElementById("result").innerHTML += i + ", ";
}

// better - update a local variable
var i, content = "";
for (i = 0; i < 100; i += 1) {
    content += i + ",";
}
document.getElementById("result").innerHTML += content;

// Stefanov, Stoyan. JavaScript patterns. Sebastopol, CA: O'Reilly, 2010.

Document Object Model

The previous examples were for accessing the DOM. You can also manipulate the DOM.

var newParagraph = document.createElement('p'),
newText = document.createTextNode('Hansel and Gretel left a breadcrumb trail...'),
newDiv = document.createElement('div'),
otherParagraph = document.createElement('p'),
otherText = document.createTextNode('Hansel shoved the witch into the oven...');

newParagraph.appendChild(newText);
otherParagraph.appendChild(otherText);
newDiv.appendChild(otherParagraph);
newDiv.insertBefore(newParagraph, otherParagraph);
document.body.appendChild(newDiv);

Document Object Model

Again, it is better to minimize DOM access by copying the DOM nodes into a variable, manipulating the variable, and then inserting the results back into the DOM.

var p, t, frag;

frag = document.createDocumentFragment();

p = document.createElement('p');
t = document.createTextNode('first paragraph');
p.appendChild(t);
frag.appendChild(p);

p = document.createElement('p');
t = document.createTextNode('second paragraph');
p.appendChild(t);
frag.appendChild(p);

document.body.appendChild(frag);

// Stefanov, Stoyan. JavaScript patterns. Sebastopol, CA: O'Reilly, 2010.

Document Object Model

Useful reference for available DOM properties and methods:

https://developer.mozilla.org/en-US/docs/DOM/DOM_Reference

Events

Examples of browser events include mouse events and keyboard events.

  • Events have targets (the element that receives the event)
  • Events 'bubble up' from the target to parent nodes in the DOM.
  • Attach event handlers to DOM nodes (as callback functions).
  • As an event bubbles, event handlers for parent nodes may fire.

Event Handling: Example 1

http://www.jspatterns.com/book/8/click.html

Event Handling: Example 2

Like example 1, but should add the following, and is attached to a parent node of the intended event target.

// get event and source element
e = e || window.event;
src = e.target || e.srcElement;

if (src.nodeName.toLowerCase() !== "button") {
return;
}
http://www.jspatterns.com/book/8/click-delegate.html

Ajax

JavaScript can make HTTP requests back to the server using an XMLHttpRequest object.

var xhr =  new XMLHttpRequest();

// When the xhr object's readyState is 4, we have a response ready.
// Need to set up an event handler callback to respond to that
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// Handle ajax response
}
}

// Make the request.
// first parameter is HTTP method, second is URL,
// final is boolean indicating whether asynchronous or not
xhr.open("GET", "page.html", true);

// If you use POST method, you can pass post data in send()
xhr.send("");

Ajax Example 1

http://www.jspatterns.com/book/8/xhr.html

Ajax Example 2

http://www.jspatterns.com/book/8/ttt.html

Exercise: JSONP

  1. Save a copy the JSONP example page at http://www.jspatterns.com/book/8/ttt.html to your computer.
  2. Modify your copy of the script so that, when the server is playing, the border of the selected cell changes color, the game pauses, and then the server places the X, the game pauses again, the border color disappears, and then after another pause, the client places the O.
  3. Modify your copy of the script so that, below the table element, you insert a message stating where the server put its X (e.g., "Server selects top left," "Server selects bottom center," "Server selects center right").

Lab Time


Finish your midterm presentation. See https://github.com/aipdx-wdim387/week4 for details.

WDIM387 Week 4 Browsers, DOM, Events, and AJAX

By danmuzyka

WDIM387 Week 4 Browsers, DOM, Events, and AJAX

  • 1,564