-1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
davidtgq
  • 3,780
  • 10
  • 43
  • 80
  • 1
    There's a good explanation on this link http://www.quirksmode.org/js/introevents.html And you may also refer to this question http://stackoverflow.com/a/12627478/4885631 – Jude Feb 22 '16 at 06:54

1 Answers1

3

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875