04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 12: Events<br />

This rewritten example works as expected because the same function is used for both<br />

addEventListener() and removeEventListener() .<br />

In most cases, event handlers are added to the bubbling phase of the event flow since this offers the<br />

broadest possible cross - browser support. Attaching an event handler in the capture phase is best done if<br />

you need to intercept events before they reach their intended target. If this is not necessary, it ’ s advisable<br />

to avoid event capturing.<br />

DOM Level 2 event handlers are supported in Firefox, Safari, Chrome, and Opera.<br />

Internet Explorer Event Handlers<br />

IE implements methods similar to the DOM called attachEvent() and detachEvent() . These<br />

methods accept the same two arguments: the event handler name and the event handler function. Since<br />

IE only supports event bubbling, event handlers added using attachEvent() are attached on the<br />

bubbling phase.<br />

To add an event handler for the click event on a button using attachEvent() , the following code can<br />

be used:<br />

var btn = document.getElementById(“myBtn”);<br />

btn.attachEvent(“onclick”, function(){<br />

alert(“Clicked”);<br />

});<br />

Note that the first argument of attachEvent() is “ onclick ” as opposed to “ click ” in the DOM ’ s<br />

addEventListener() method.<br />

A major difference between using attachEvent() and using the DOM Level 0 approach in IE is the<br />

scope of the event handler. When using DOM Level 0, the event handler runs in the scope of the element<br />

on which it is attached; when using attachEvent() , the event handler runs in the global scope, so this<br />

is equivalent to window . Here is an example:<br />

var btn = document.getElementById(“myBtn”);<br />

btn.attachEvent(“onclick”, function(){<br />

alert(this === window); //true<br />

});<br />

This difference is important to understand when writing cross - browser code.<br />

372

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!