0

I've seen two different ways to aproach it:

$('#element').on('click', function(){
    /* do stuff */
});

Or:

 $('#element').click(function(){
    /* do stuff */
});

which is the correct/better way?

divy3993
  • 5,732
  • 2
  • 28
  • 41
  • 5
    They are both identical. If you [check the source](https://j11y.io/jquery/#v=1.11.2&fn=jQuery.fn.click), `click()` calls `on('click', fn)` internally anyway. There are some who say you should only use `on()`, but that is purely a preference. There is no logical reason for it – Rory McCrossan Jun 29 '17 at 12:03
  • @RoryMcCrossan the only difference is that using .on() you can set a namespace to the event. Example: .on('click.somename', function() {}) – Christian Benseler Jun 29 '17 at 12:06
  • True, however I was talking more in the context of usage in the OPs example – Rory McCrossan Jun 29 '17 at 12:07
  • it is better to use `on` because you can then use [events' namespaceing](https://api.jquery.com/event.namespace/): `.on("click.fun", cb)`... – vsync Jun 29 '17 at 12:11

1 Answers1

0

.On() function was introduced in Jquery 1.7, it is better and more preferred method to call the event. whereas if you are looking for backward compatibility then choose the other one.

MrWaqasAhmed
  • 1,479
  • 12
  • 12