-
<div id="myDiv" onclick="MyFunc()"></div> -
document.getElementById("myDiv").onclick = MyFunc; -
document.getElementById("myDiv").addEventListener("click", MyFunc, false)
Now, what is the difference between these 3 ways of attaching an event to a DOM element (ignoring the fact that 3 won’t work on IE)?
Methods A and B
These are known as DOM level zero events and are somewhat old school. Method A declares it in-line in your HTML (bad) where as method B does the same thing but centrally, in your JS.
With method A, the attribute value is a string of valid JS that, on firing, will be evaluated (also bad). Due to the position in which the event is being bound, this means any functions referenced in this string must be global (or globally accessible methods). With method B, the event is bound centrally, in your JS, rather than inline.
The main caveat with them, aside from being outdated and simplified, is that you can bind only one kind of event per element. If you attempt to bind two click event handlers to the same event handler with this mechanism, the first will be forgotten. This stands to reason, since you are simply overwriting an element attribute.
Method C
addEventListeneris the standard for attaching events. For a long time, IE didn’t support this, favouring its equivalentattachEventmethod. Some differences between them include:attachEventdoes not allow capturing of events (param 3 ofaddEventListenerallows this)attachEvent, the event object (i.e. the object that stores information about the fired event) is accessed onwindow.event, whereas withaddEventListenerit is forwarded as the only argument to the callbackattachEvent, event names must be prefixed withon, e.g.onClick.addEventListenerrequires simplyclickaddEventListener, thethiskeyword inside the callback points to the element that triggered the event. InattachEventyou have to decipher this yourself by extrating the element from properties within the event (window.event) objectIE9 came into line and supports
addEventListener.