// attach playNewGame click handler when page has finished loading
document.observe('dom:loaded', function () {
$('play').observe('click', playNewGame);
});
allows multiple scripts to run "onload" handlers when the page has finished loading
Attaching multiple event handlers with $$
// listen to clicks on all buttons with class "control" that
// are directly inside the section with ID "game"
document.observe('dom:loaded', function() {
var gameButtons = $$("#game > button.control");
for (var i = 0; i < gameButtons.length; i++) {
gameButtons[i].observe("click", gameButtonClick);
}
});
function gameButtonClick() { ... }
you can use $$ and other DOM walking methods to unobtrusively attach event handlers to a group of related elements in your window.onload code
The event object
function name(event) {
// an event handler function ...
}
Event handlers can accept an optional parameter to represent the event that is occurring. Event objects have the following properties / methods:
method / property name
description
type
what kind of event, such as "click" or "mousedown"
this.fieldName// access field
this.fieldName = value; // modify field
this.methodName(parameters); // call method
all JavaScript code actually runs inside of an object
by default, code runs in the global window object (so this === window)
all global variables and functions you declare become part of window
the this keyword refers to the current object
Event handler binding
document.observe('dom:loaded', 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 onthis.value = "booyah";
}
event handlers attached unobtrusively are bound to the element
inside the handler, that element becomes this (rather than the window)
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!");
}
if the same function is assigned to multiple elements, each gets its own bound copy
style property lets you set any CSS style for an element
problem: you cannot (usually) read existing styles with it
Accessing styles in Prototype
(9.1.4)
function biggerFont() {
// turn text yellow and make it bigger
var size = parseInt($("clickme").getStyle("font-size"));
$("clickme").style.fontSize = (size + 4) + "pt";
}
getStyle function added to DOM object allows accessing existing styles