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.
JavaScript events
-
the
click
event (onclick
) is just one of many events that can be handled
-
problem: events are tricky and have incompatibilities across browsers
-
reasons: fuzzy W3C event specs; IE disobeying web standards; etc.
-
solution: Prototype includes many event-related features and fixes
Attaching event handlers the Prototype way
element.onevent = function;
element.observe("event", "function");
$("play").observe("click", playNewGame);
-
to use Prototype's event features, you must attach the handler using the DOM element object's
observe
method (added by Prototype)
-
pass the event name as a string, and the function name to call
-
handlers must be attached this way for Prototype's event features to work
Attaching multiple event handlers with $$
window.onload = 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) {
}
-
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"
|
element() *
|
the element on which the event occurred
|
stop() **
|
cancels an event
|
stopObserving()
|
removes an event handler
|
-
* replaces non-standard
srcElement
and which
properties
-
** replaces non-standard
return false;
, stopPropagation
, etc.
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:
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
|
-
* replaces non-standard properties
pageX
and pageY
-
** replaces non-standard properties
button
and which
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 + ")";
}
The keyword this
(8.1.3)
this.fieldName
this.fieldName = value;
this.methodName(parameters);
-
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
- event handlers attached unobtrusively are bound to the element
- inside the handler, that element becomes
this
(rather than the window
)
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!");
}
- if the same function is assigned to multiple elements, each gets its own bound copy
Page/window events
(9.2.5)
name | description |
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
|
-
The above can be handled on the
window
object. An alternative to window.onload
:
window.onload = function() { ... };
document.observe("dom:loaded", function() {
});
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
|
-
Prototype adds the following methods to form controls' DOM objects:
Prototype form shortcuts
(9.1.6)
$("formID")["name"]
-
gets parameter with given name from form with given id
$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.");
event.stop();
return false;
}
}
- to abort a form submit or other event, call Prototype's
stop
method on the event
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)
|
-
focus: the attention of the user's keyboard (given to one element at a time)
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
|
|
|
|
-
issue: if the event you attach your listener to doesn't have the focus, you won't hear the event
-
possible solution: attach key listener to entire page body, outer element, etc.