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
addEventListener
is the standard for attaching events. For a long time, IE didn't support this, favouring its equivalent attachEvent
method. Some differences between them include:
attachEvent
does not allow capturing of events (param 3 of addEventListener
allows this)
- with
attachEvent
, the event object (i.e. the object that stores information about the fired event) is accessed on window.event
, whereas with addEventListener
it is forwarded as the only argument to the callback
- with
attachEvent
, event names must be prefixed with on
, e.g. onClick
. addEventListener
requires simply click
- with
addEventListener
, the this
keyword inside the callback points to the element that triggered the event. In attachEvent
you have to decipher this yourself by extrating the element from properties within the event (window.event
) object
IE9 came into line and supports addEventListener
.