I have found four variations of this so far.
addEventListener('click')
is the native method and performs best.
Then jQuery wraps it to be compatible with some obsolete browsers while reducing performance by an order of magnitude, with three different methods:
on('click')
click()
onclick()
Why does there exist so many? What is the history/reasoning behind their existence? And briefly, are there differences in their use cases or limitations to each?
I have found four variations of this so far.
Well, no. Two of those are the DOM, not jQuery. There is no addEventListener
or onclick
on jQuery instances. They're on DOM elements.
So why does jQuery have both on
and click
? Maybe the documentation can tell us:
click
This method is a shortcut for
.on( "click", handler )
It's just a shortcut, seven characters instead of 11 (13 originally, see below), for when the event name is known at coding time (rather than runtime, when we might pass a variable into on
). (There's also another form of click
: If you call it without arguments, it triggers the event rather than hooking up a handler.)
You forgot bind
, which is an earlier version of on
. on
was added in v1.7 to combine the functionality of bind
, delegate
, and live
. Retrofitting bind
would have required breaking changes, and the word bind
was increasingly coming to mean something else entirely. So they went with on
, since the DOM uses the "on" prefix (onclick
, onmousemove
, onfocus
, ...), both in DOM element properties you can assign functions to, and as attributes you can put code in in the markup.
jQuery also has one
, which is similar to on
but automatically removes the handler on first use.
Bottom line: All APIs evolve over time.