SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 86 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"

stopPropagation();
For more information, refer to the W3C documentation at www.w3.org/TR/DOM-Level-3-
Events/events.html#Events-flow. Event capturing isn??™t supported in IE, so it therefore tends
not to be used.
Attaching Events in IE
The largest problem with events is that event handling is different in IE than the other
browsers. It uses a method called attachEvent() and takes only two parameters: the event
name (with on), and the function you want called:
element.attachEvent('onclick', functionname);
To get around this difference, you need to fork the code. You can encapsulate the event
listener code into a function that you can reuse:
function addListener(element, event, listener) {
if (element.addEventListener){
element.addEventListener(event, listener, false);
} else if (element.attachEvent){
element.attachEvent('on'+event, listener);
}
}
Now, you can add multiple event handlers to a single event:
addListener(window, 'load', foo);
addListener(window, 'load', bar);
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 45
Using event listeners are quite handy, but handling the event has become a little trickier.
Remember the this keyword? When using attachEvent() in IE, the this keyword doesn??™t refer
to the object to which you attached the event; it refers to the window object.
Let??™s demonstrate the problem:
// assume we have an a element on the page with an id of mylink
var mylink = document.


Pages:
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98