Intro to DOM and Timers

CSE 190 M (Web Programming) Spring 2008

University of Washington

Reading: Chapter 3 sections 3.2 - 3.3

Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp and Jessica Miller and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.1 Valid CSS!

Lecture Outline

Introduction to the Document Object Model (DOM)

Used to manipulate XHTML page elements in your JS code

Basic idea

What is the DOM?


Accessing elements: The $ function

<span id="sale">Blowout sale!</span>
<button onclick="makeRed();">Make Text Red</button>
function makeRed() {
	$("sale").style.color = "red";
Blowout sale!

More about the $ function

function $(id) {
	return document.getElementById(id);

Manipulating DOM objects

<input id="username" type="text" size="12" />
<button onclick="capitalize();">Capitalize It!</button>
function capitalize() {
	$("username").value = $("username").value.toUpperCase();

More DOM object properties

<div id="main" class="foo bar">
	<p>Hello, <em>very</em> happy to see you!</p>

DOM style property

<button id="clickme" onclick="enlarge();">
Make me big!</button>
function enlarge() {
	$("clickme").style.fontSize = "42pt";

Common DOM styling errors

JavaScript timers and animation

Repeatedly executing an event handler at timed intervals

Timer concepts


Timer functions

setTimeout example

function delayMsg() {
	setTimeout(booyah, 5000);
function booyah() {   // called when the timer goes off
<button onclick="delayMsg();">Click me!</button>

setInterval example

function repeatedMessage() {
	setInterval(rudyRudy, 1000);
function rudyRudy() {
<button onclick="repeatedMessage();">Click me!</button>

Clearing a timer

var timer;
function repeatedMessage() {
	timer = setInterval(rudyRudy, 1000);
function rudyRudy() {
function cancel() {
<button onclick="repeatedMessage();">Rudy chant</button>
<button onclick="cancel();">Make it stop!</button>

Passing parameters to timers

function delayedMultiply() {
	// 6 and 7 are passed to multiply when timer goes off
	var myTimer = setTimeout(multiply, 2000, 6, 7);
function multiply(a, b) {
	alert(a * b);
<button onclick="delayedMultiply();">Click me</button>

Common timer errors

Alternate timer syntax, as a String

function delayedMultiply() {
	var myTimer = setTimeout("multiply(6 * 7);", 2000);
function multiply(a, b) {
	alert(a * b);
<button onclick="delayedMultiply();">Click me!</button>