Web Programming Step by Step, 2nd Edition

Lecture 20: Events and Timers

Reading: 11.1

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.1: Global DOM Objects

The six global DOM objects

Every Javascript program can refer to the following global objects:

namedescription
document current HTML page and its content
history list of pages the user has visited
location URL of the current HTML page
navigator info about the web browser you are using
screen info about the screen area occupied by the browser
window the browser window

The window object

the entire browser window; the top-level object in DOM hierarchy

Popup windows with window.open

window.open("http://foo.com/bar.html", "My Foo Window",
            "width=900,height=600,scrollbars=1");

The document object

the current web page and the elements inside it

The location object

the URL of the current web page

The navigator object

information about the web browser application

The screen object

information about the client's display screen

The history object

the list of sites the browser has visited in this window

Timers

Setting a timer

timer
method description
setTimeout(functiondelayMS); arranges to call given function after given delay in ms
setInterval(functiondelayMS); arranges to call function repeatedly every delayMS ms
clearTimeout(timerID);
clearInterval(timerID);
stops the given timer

setTimeout example

<button id="clickme">Click me!</button>
<span id="output"></span>
window.onload = function() {
	document.getElementById("clickme").onclick = delayedMessage;
};

function delayedMessage() {
	document.getElementById("output").innerHTML = "Wait for it...";
	setTimeout(sayBooyah, 5000);
}

function sayBooyah() {   // called when the timer goes off
	document.getElementById("output").innerHTML = "BOOYAH!";
}

setInterval example

var timer = null;  // stores ID of interval timer

function delayMsg2() {
	if (timer === null) {
		timer = setInterval(rudy, 1000);
	} else {
		clearInterval(timer);
		timer = null;
	}
}

function rudy() {   // called each time the timer goes off
	document.getElementById("output").innerHTML += " Rudy!";
}

Passing parameters to timers

function delayedMultiply() {
	// 6 and 7 are passed to multiply when timer goes off
	setTimeout(multiply, 2000, 6, 7);
}
function multiply(a, b) {
	alert(a * b);
}

Common timer errors