18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9<br />

As previously stated, this method can be used to attach more than one event handler:<br />

var fnClick1 = function () {<br />

alert(“Clicked!”);<br />

};<br />

var fnClick2 = function () {<br />

alert(“Also clicked! “);<br />

};<br />

var oDiv = document.getElementById(“div”);<br />

oDiv.attachEvent(“onclick”, fnClick1);<br />

oDiv.attachEvent(“onclick”, fnClick2);<br />

This code segment causes two alerts to be displayed when you click the element. The first is<br />

“Clicked!”, followed by “Also clicked!”. The event handlers always execute in the order in which<br />

they are added.<br />

You can also use the traditional <strong>JavaScript</strong> method of assigning event handlers:<br />

var fnClick1 = function () {<br />

alert(“Clicked!”);<br />

};<br />

var fnClick2 = function () {<br />

alert(“Also clicked! “);<br />

};<br />

var oDiv = document.getElementById(“div”);<br />

oDiv.onclick = fnClick1;<br />

oDiv.attachEvent(“onclick”, fnClick2);<br />

This code is exactly equal to the previous example, and the alerts are displayed in the same order.<br />

Assigning an event handler in the traditional way is considered just another call to attachEvent(),<br />

so the event handlers are still executed in the order in which they are defined.<br />

DOM<br />

268<br />

The DOM methods addEventListener() and removeEventListener() accomplish the assignment<br />

and removal of event handlers. These methods, unlike IE, take three parameters: the event name, the<br />

function to assign, and whether the handler should be used for the bubbling or capture phase. If the handler<br />

is to be used in the capture phase, the third parameter is true; for the bubbling phase, it is false.<br />

Here’s the general syntax:<br />

[Object].addEventListener(“name_of_event”, fnHandler, bCapture);<br />

[Object].removeEventListener(“name_of_event”, fnHandler, bCapture);<br />

To use these methods, you must first get a reference to the object in question and then assign or remove<br />

the event handlers:<br />

var fnClick = function () {<br />

alert(“Clicked!”);<br />

};

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

Saved successfully!

Ooh no, something went wrong!