Web Programming Step by Step

Lecture 16
Events

Reading: 9.1 - 9.2

Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.

Valid XHTML 1.1 Valid CSS!

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);

Attaching multiple event handlers with $$

// listen to clicks on all buttons with class "control" that
// are directly inside the section with ID "game"
window.onload = function() {
	var gameButtons = $$("#game > button.control");
	for (var i = 0; i < gameButtons.length; i++) {
		gameButtons[i].observe("click", gameButtonClick);
	}
};

function gameButtonClick() { ... }

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 (9.2.2)

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 (8.1.3)

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 (9.2.5)

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.
});

Form events (9.1.6, 9.2.4)

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 (9.1.6)

$("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;
	}
}

Keyboard/text events (9.2.3)

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