-3

I'm curious.

for example, if I want to add an event listener for click

I normally use jQuery

$('.selector').click(function() {} );

but there are several others ways of doing it too

<button class="selector" id="selector" onclick="click()">

$('.selector').on('click', function() {} );

document.getElementById('selector').addEventListener("click", function() {} );

Are there any notable difference between them ?

What are the best practices ?

Steve
  • 1,553
  • 2
  • 20
  • 29
Jacob Goh
  • 19,800
  • 5
  • 53
  • 73
  • 1
    The first one is [not unobtrusive](http://stackoverflow.com/q/8392374/11683). The second one uses jQuery. The third one does not use jQuery and [will not work](http://stackoverflow.com/q/6348494/11683) on IE < 9. – GSerg Aug 07 '16 at 07:24
  • as well as what @GSerg mentioned about not working in IE8 and below, using jQuery `on` you can attach multiple event like `on('click change input')`, AFAIK you can't do that *directly* in pure javascript, check this [blog.garstasio.com/you-dont-need-jquery/events](http://blog.garstasio.com/you-dont-need-jquery/events/) – Mi-Creativity Aug 07 '16 at 07:29
  • 1
    jQuery abstracts some of the details for you, so you don't have to worry about implementation differences in old browsers, not that that matters so much these days now that old versions of IE aren't much used. But jQuery also makes it very simple to bind handlers to multiple elements with one line of code, etc. I wouldn't add jQuery to a project *just* for event handling, because it's easy enough to do it with vanilla JS, but if I needed other convenience features like easy DOM navigation, simple animations, one-line Ajax, etc., then I would use jQuery. – nnnnnn Aug 07 '16 at 07:31
  • these are very helpful. Thanks! – Jacob Goh Aug 07 '16 at 07:47

1 Answers1

0

It depends. I usually use this one:

$('body').on('click', '.selector', function() {} );

because it add's listener to all elements with that class, even for the elements that will come later to the document (ie. after AJAX calls).

daymosik
  • 140
  • 8
  • While the observed effect is that it indeed adds a listener to future elements, in fact it only adds one listener to `body`, and the entire point is not relevant to the OP's question. – GSerg Aug 07 '16 at 07:28