Main Page

DOM

As previously stated, this method can be used to attach more than one event handler:
var fnClick1 = function () {
alert(“Clicked!”);
};
var fnClick2 = function () {
alert(“Also clicked! “);
};
var oDiv = document.getElementById(“div”);
oDiv.attachEvent(“onclick”, fnClick1);
oDiv.attachEvent(“onclick”, fnClick2);
This code segment causes two alerts to be displayed when you click the
<div/>
element. The first is
“Clicked!”
, followed by
“Also clicked!”
. The event handlers always execute in the order in which
they are added.
You can also use the traditional JavaScript method of assigning event handlers:
var fnClick1 = function () {
alert(“Clicked!”);
};
var fnClick2 = function () {
alert(“Also clicked! “);
};
var oDiv = document.getElementById(“div”);
oDiv.onclick = fnClick1;
oDiv.attachEvent(“onclick”, fnClick2);
This code is exactly equal to the previous example, and the alerts are displayed in the same order.
Assigning an event handler in the traditional way is considered just another call to
attachEvent()
,
so the event handlers are still executed in the order in which they are defined.
DOM
The DOM methods
addEventListener()
and
removeEventListener()
accomplish the assignment
and removal of event handlers. These methods, unlike IE, take three parameters: the event name, the
function to assign, and whether the handler should be used for the bubbling or capture phase. If the han-
dler is to be used in the capture phase, the third parameter is
true
; for the bubbling phase, it is
false
.
Here’s the general syntax:
[Object].
addEventListener(“name_of_event”, fnHandler, bCapture);
[Object].
removeEventListener(“name_of_event”, fnHandler, bCapture);
To use these methods, you must first get a reference to the object in question and then assign or remove
the event handlers:
var fnClick = function () {
alert(“Clicked!”);
};
268
Chapter 9
12_579088 ch09.qxd 3/28/05 11:39 AM Page 268


JavaScript EditorFree JavaScript Editor     Ajax Editor


©