Web Programming Step by Step, 2nd Edition

Lecture 17: The Document Object Model (DOM); Unobtrusive JavaScript

Reading: 9.1 - 9.2

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

9.2: DOM Element Objects

Document Object Model (DOM)

a set of JavaScript objects that represent each element on the page

DOM

DOM element objects

dom object

Accessing an element: document.getElementById

var name = document.getElementById("id");
<img id="icon01" src="images/octopus.jpg" alt="an animal" />
<button onclick="changeImage();">Click me!</button>
function changeImage() {
	var octopusImage = document.getElementById("icon01");
	octopusImage.src = "images/kitty.gif";
}

DOM object properties

<div id="main" class="foo bar">
	<p>See our <a href="sale.html" id="saleslink">Sales</a> today!</p>
	<img id="icon" src="images/borat.jpg" alt="Borat" />
</div>
var mainDiv = document.getElementById("main");
var icon    = document.getElementById("icon");
var theLink = document.getElementById("saleslink");
Property Description Example
tagName element's HTML tag mainDiv.tagName is "DIV"
className CSS classes of element mainDiv.className is "foo bar"
innerHTML content in element mainDiv.innerHTML is "\n <p>See our <a hr...
src URL target of an image icon.src is "images/borat.jpg"
href URL target of a link theLink.href is "sale.html"

DOM properties for form controls

<input id="sid" type="text" size="7" maxlength="7" />
<input id="frosh" type="checkbox" checked="checked" /> Freshman?
var sid   = document.getElementById("sid");
var frosh = document.getElementById("frosh");
Property Description Example
value the text/value chosen by the user sid.value could be "1234567"
checked whether a box is checked frosh.checked is true
disabled whether a control is disabled (boolean) frosh.disabled is false
readOnly whether a text box is read-only sid.readOnly is false

More about form controls

<select id="captain">
	<option value="kirk">James T. Kirk</option>
	<option value="picard">Jean-Luc Picard</option>
	<option value="cisco">Benjamin Cisco</option>
</select>
<label> <input id="trekkie" type="checkbox" /> I'm a Trekkie </label>

The innerHTML property

<button onclick="addText();">Click me!</button>
<span id="output">Hello </span>
function addText() {
	var span = document.getElementById("output");
	span.innerHTML += " bro";
}

Abuse of innerHTML

// bad style!
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "<p>text and <a href=\"page.html\">link</a>";

Adjusting styles with the DOM

objectName.style.propertyName = "value";
<button onclick="colorIt();">Click me!</button>
<span id="fancytext">Don't forget your homework!</span>
function colorIt() {
	var text = document.getElementById("fancytext");
	text.style.color = "#ff5500";
	text.style.fontSize = "40pt";
}
Property Description
style lets you set any CSS style property for an element

Common DOM styling errors

9.1.1: Unobtrusive JavaScript

Unobtrusive JavaScript

Obtrusive event handlers (bad)

<button onclick="okayClick();">OK</button>
// called when OK button is clicked
function okayClick() {
	alert("booyah");
}

Attaching an event handler in JavaScript code

objectName.onevent = function;
<button id="ok">OK</button>
var okButton = document.getElementById("ok");
okButton.onclick = okayClick;

When does my code run?

<html>
	<head>
		<script src="myfile.js" type="text/javascript"></script>
	</head>
	<body> ... </body> </html>
var x = 3;
function f(n) { return n + 1; }
function g(n) { return n - 1; }
x = f(x);

A failed attempt at being unobtrusive

<html>
	<head>
		<script src="myfile.js" type="text/javascript"></script>
	</head>
	<body>
		<div><button id="ok">OK</button></div>
var ok = document.getElementById("ok");
ok.onclick = okayClick;   // error: null

The window.onload event

function functionName() {
	// code to initialize the page
	...
}

// run this function once the page has finished loading
window.onload = functionName;

An unobtrusive event handler

<button id="ok">OK</button>               <!-- (1) -->
// called when page loads; sets up event handlers
function pageLoad() {
	var ok = document.getElementById("ok");   // (3)
	ok.onclick = okayClick;
}

function okayClick() {
	alert("booyah");                          // (4)
}

window.onload = pageLoad;                   // (2)

Common unobtrusive JS errors

Anonymous functions

function(parameters) {
	statements;
}

Anonymous function example

window.onload = function() {
	var ok = document.getElementById("ok");
	ok.onclick = okayClick;
};

function okayClick() {
	alert("booyah");
}
window.onload = function() {
	document.getElementById("ok").onclick = function() {
		alert("booyah");
	};
};

Unobtrusive styling

function okayClick() {
	this.style.color = "red";
	this.className = "highlighted";
}
.highlighted { color: red; }

The danger of global variables

var count = 0;
function incr(n) {
  count += n;
}
function reset() {
  count = 0;
}

incr(4);
incr(2);
console.log(count);

Enclosing code in a function

function everything() {
	var count = 0;
	function incr(n) {
		count += n;
	}
	function reset() {
		count = 0;
	}

	incr(4);
	incr(2);
	console.log(count);
}

everything();   // call the function to run the code

The "module pattern"

(function() {
    statements;
})();

Module pattern example

(function() {
	var count = 0;
	function incr(n) {
		count += n;
	}
	function reset() {
		count = 0;
	}

	incr(4);
	incr(2);
	console.log(count);
})();

JavaScript "strict" mode

screenshot
"use strict";

your code...