Assigning event handlers in the DOM
In light of the new event flow (event capture and event bubble) that occurs inside the DOM, new methods for assigning event handlers are introduced to harness it. Below we discuss how to assign event handlers to elements using the DOM, or more specifically, the DOM of NS6 and IE5, respectively.
Assigning event handlers in NS6+/Firefox
NS6+/Firefox fully embraces the proposed DOM event flow- event capture then event bubble. To tame this circling beast, a concept for attaching event handlers is introduced- event listeners. Oh no, here comes an earful. Actually, event listeners can be summed up using just two methods.
object.addEventListener(event, function, capture) object.removeEventListener(event, function, capture)
-event should contain the event you wish to detect, such as
click (onclick minus the "on" prefix)
The first method assigns an event handler, while the second obviously allows you to then remove it.
Let's use this knowledge to attach an onMousever event to a DIV in NS6+/Firefox:
Moving your mouse over the DIV now will cause an alert message to popup.
One cool thing about addEventListener() is that it can be used multiple times to attach multiple functions to the same event for the same element. For example, we can have 3 separate onMouseover events for the DIV above:
document.getElementById("test").addEventListener("mouseover",alertthis,false) document.getElementById("test").addEventListener("mouseover",alertdat,false) document.getElementById("test").addEventListener("mouseover",alerttidat,false)
and all three will be responded to onMouseover. Finally two scripts can both apply the same event handler to an element without the former being cancelled out.
Using object.removeEventListener(), you can dynamically remove an event handler added using its counterpart. When doing so, the 3 parameters must be identical to the ones used to add the event.
Assigning event handlers in IE5+
In IE5+, the DOM is more simplistic in that it focuses simply on events bubbling up. In other words, the event flow of IE5+ is half that of NS6's. Good thing it retains the better half :)
Two proprietary methods are supported for assigning event handlers in the DOM of IE5+:
object.attachEvent(eventname, function) object.detachEvent(eventname, function)
-eventname should contain the full event name you wish to
detect, such as onclick
Let's replicate the above <DIV>, but attach the event IE5+ style:
All this talk of event flow and assigning event handlers is begging for a good example using them. Well, here it is...