Main Page


var oDiv = document.getElementById(“div1”);
oDiv.addEventListener(“click”, fnClick, false); //add the event handler
//do some other stuff here
oDiv.removeEventListener(“click”, fnClick, false); //remove the event
And just as in IE, you can attach more than one event handler:
var fnClick1 = function () {
var fnClick2 = function () {
alert(“Also clicked!”);
var oDiv = document.getElementById(“div1”);
oDiv.addEventListener(“onclick”, fnClick1);
oDiv.addEventListener(“onclick”, fnClick2);
This code displays
and then
“Also clicked!”
when the user clicks on the
Similar to IE, the event handlers are executed in the order in which they are defined.
If an event handler is added in the capturing phase using
, the capturing phase
must be specified in
for it to be properly removed. For instance, don’t do this:
var fnClick = function () {
var oDiv = document.getElementById(“div1”);
//add the event handler in the bubbling phase
oDiv.addEventListener(“click”, fnClick, false);
//do some other stuff here
//try to remove the event handler, but the third parameter is true
//instead false...this will fail, though it won’t cause an error.
oDiv.removeEventListener(“click”, fnClick, true);
Here, the function
is added in the bubbling phase, and then an attempt is made to remove it
from the capture phase. This won’t cause an error, but the function won’t be removed.
If you use the traditional way of assigning a function directly to the event handler property, the event
handler is added in the bubbling phase of the event. For example, the following two lines achieve the
same effect:
oDiv.onclick = fnClick;
oDiv.addEventListener(“click”, fnClick, false);
The direct assignment of an event handler is considered to be just another call to
so the event handlers are used in the order in which they are specified.
All about Events
12_579088 ch09.qxd 3/28/05 11:39 AM Page 269

JavaScript EditorFree JavaScript Editor     Ajax Editor