Web Programming Step by Step, 2nd Edition
Lecture 20: Events; Global DOM Objects
Reading: 11.1; 9.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.
11.1: Event-Handling
-
11.1: Event-Handling
- 11.1.1 The Event Object
- 11.1.2 Mouse Events
- 11.1.3 Keyboard and Text Events
- 11.1.4 Form Events
- 11.1.5 Page Events
- 11.1.6 Timer Events
-
11.2: Case Study: Multiplication Quiz
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
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
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
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
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() {
});
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)
|
-
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.
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
|
-
Prototype adds the following methods to form controls' DOM objects:
Prototype form shortcuts
$F("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
9.1: Global DOM Objects
-
9.1: Global DOM Objects
-
9.2: DOM Element Objects
-
9.3: The DOM Tree
The six global DOM objects
Every Javascript program can refer to the following global objects:
name | description |
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 entire browser window; the top-level object in DOM hierarchy
- technically, all global code and variables become part of the
window
object
- properties:
- methods:
-
alert
,
confirm
,
prompt
(popup boxes)
-
setInterval
,
setTimeout
clearInterval
,
clearTimeout
(timers)
-
open
,
close
(popping up new browser windows)
-
blur
,
focus
,
moveBy
,
moveTo
,
print
,
resizeBy
,
resizeTo
,
scrollBy
,
scrollTo
Popup windows with window.open
window.open("http://foo.com/bar.html", "My Foo Window",
"width=900,height=600,scrollbars=1");
window.open
pops up a new browser window
- THIS method is the cause of all the terrible popups on the web!
- some popup blocker software will prevent this method from running
the current web page and the elements inside it
the URL of the current web page
information about the web browser application
information about the client's display screen
the list of sites the browser has visited in this window
- properties:
- methods:
- complete list
- sometimes the browser won't let scripts view
history
properties, for security