Assigning an event listener to an element using XHTML, ECMAScript, and DOM Level 2. First define a function that will be used to catch the events; the function takes a single Event object as a parameter:
/** Display the title of the target of the Event. */
function catchEvent(e) {
alert(e.target.getAttribute("title"));
}
The DOM Way is to add an event listener using the addEventListener method:
<button id="first" type="button"
title="This event was added using the DOM
addEventListener method">DOM</button>
<script type="text/javascript">
// <![CDATA[
// If the implementation supports DOM Level 2 mouse
// events, add event listeners to buttons. */
if (document.implementation
&& document.implementation.hasFeature
&& document.implementation.hasFeature("MouseEvents",
"2.0")) {
document.getElementById("first")
.addEventListener("click", catchEvent, true);
}
// ]]>
</script>
The second argument of addEventListener is an ECMAScript function reference for a function that has no return value and takes a single Event object as a parameter
Test:
The XHTML Way is to add the event listener using the onclick attribute:
<button id="second" onclick="catchEvent(event);"
title="This event was added using the XHTML
onclick attribute">XHTML</button>
Test: