Web Programming Step by Step, 2nd Edition

Chapter 11: Events

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 XHTML 1.1 Valid CSS!

11.1: Event-Handling

JavaScript events

abort blur change click dblclick error focus
keydown keypress keyup load mousedown mousemove mouseout
mouseover mouseup reset resize select submit unload

Attaching event handlers the Prototype way

element.onevent = function;
element.observe("event", function);
// call the playNewGame function when the Play button is clicked
$("play").observe("click", playNewGame);

The event object

function name(event) {
	// an event handler function ...
}
method / property name description
type what kind of event, such as "click" or "mousedown"
element() * the element on which the event occurred
stop() ** cancels an event
stopObserving() removes an event handler

Mouse events

clicking
click user presses/releases mouse button on the element
dblclick user presses/releases mouse button twice on the element
mousedown user presses down mouse button on the element
mouseup user releases mouse button on the element
movement
mouseover mouse cursor enters the element's box
mouseout mouse cursor exits the element's box
mousemove mouse cursor moves around within the element's box

Mouse event objects

The event passed to a mouse handler has these properties:

mouse event
property/method description
clientX, clientY coordinates in browser window
screenX, screenY coordinates in screen
offsetX, offsetY coordinates in element (non-standard)
pointerX(),
pointerY() *
coordinates in entire web page
isLeftClick() ** true if left button was pressed

Mouse event example

<pre id="target">Move the mouse over me!</pre>
window.onload = function() {
	$("target").observe("mousemove", showCoords);
};

function showCoords(event) {
	$("target").innerHTML = 
		  "pointer: (" + event.pointerX() + ", " + event.pointerY() + ")\n"
		+ "screen : (" + event.screenX + ", " + event.screenY + ")\n"
		+ "client : (" + event.clientX + ", " + event.clientY + ")";
}
Move the mouse over me!

The keyword this

this.fieldName                  // access field
this.fieldName = value;          // modify field

this.methodName(parameters);    // call method

Event handler binding

window.onload = function() {
	$("textbox").observe("mouseout", booyah);   // bound to text box here
	$("submit").observe("click", booyah);       // bound to submit button here
};

function booyah() {           // booyah knows what object it was called on
	this.value = "booyah";
}

Fixing redundant code with this

<fieldset>
	<label><input type="radio" name="ducks" value="Huey"  /> Huey</label>
	<label><input type="radio" name="ducks" value="Dewey" /> Dewey</label>
	<label><input type="radio" name="ducks" value="Louie" /> Louie</label>
</fieldset>
function processDucks() {
	if ($("huey").checked) {
		alert("Huey is checked!");
	} else if ($("dewey").checked) {
		alert("Dewey is checked!");
	} else {
		alert("Louie is checked!");
	}
	alert(this.value + " is checked!");
}

Page/window events

namedescription
load, unload the browser loads/exits the page
resize the browser window is resized
error an error occurs when loading a document or an image
contextmenu the user right-clicks to pop up a context menu
window.onload = function() { ... };
document.observe("dom:loaded", function() {
	// attach event handlers, etc.
});

Keyboard/text events

name description
keydown user presses a key while this element has keyboard focus
keyup user releases a key while this element has keyboard focus
keypress user presses and releases a key while this element has keyboard focus
focus this element gains keyboard focus
blur this element loses keyboard focus
select this element's text is selected or deselected)

Key event objects

property name description
keyCode ASCII integer value of key that was pressed
(convert to char with String.fromCharCode)
altKey, ctrlKey, shiftKey true if Alt/Ctrl/Shift key is being held
Prototype's key code constants
Event.KEY_BACKSPACE Event.KEY_DELETE Event.KEY_DOWN Event.KEY_END
Event.KEY_ESC Event.KEY_HOME Event.KEY_LEFT Event.KEY_PAGEDOWN
Event.KEY_PAGEUP Event.KEY_RETURN Event.KEY_RIGHT Event.KEY_TAB
Event.KEY_UP

Form events

event name description
submit form is being submitted
reset form is being reset
change the text or state of a form control has changed
activate clear disable enable
focus getValue present select

Prototype form shortcuts

$F("formID")["name"]
$F("controlID")

Stopping an event

<form id="exampleform" action="http://foo.com/foo.php">...</form>
window.onload = function() {
	$("exampleform").observe("submit", checkData);
};

function checkData(event) {
	if ($F("city") == "" || $F("state").length != 2) {
		alert("Error, invalid city/state.");  // show error message 
		event.stop();
		return false;
	}
}

Timer events

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 so it will not call its function

setTimeout example

<button onclick="delayMsg();">Click me!</button>
<span id="output"></span>
function delayMsg() {
	setTimeout(booyah, 5000);
	document.getElementById("output").innerHTML = "Wait for it...";
}

function booyah() {   // 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