0

What is the difference between using on() and click() in jquery.?

For example:Both work the same way:

    $(".classname").click( function() {
       var toAdd = $('input[name=checkListItem]').val();
    });

    $(".classname").on("click", function () {
    var toAdd = $('input[name=checkListItem]').val();
    });

When should i use .on() and when to use click(). If both are same which one should be used?

1

2 Answers 2

11

Both the syntax used above are the same...... the .click() is a short cut to the .on() call

The difference is when you use the event delegation syntax which is supported by only .on()

Ex:

$(document).on("click", ".classname", function () {
    var toAdd = $('input[name=checkListItem]').val();
});

When you use the syntax used by you it registers the handlers to only those elements which are present at the time when the code was executed, if a new element with the same class is added later then the handler will not be triggered if that one is clicked.

Event delegation is the solution for this problem... here we register the handler to a parent element which will be present in the dom with a filter criteria passed as the second argument... when the event gets bubbled upto the parent element it tests the target and its ancestors against the filter selector, if it is satisfied then the handler will get executed.

1
  • 1
    + .on() supports several events like .on('keyup click doubleclick')
    – Daniel W.
    Commented Oct 2, 2013 at 11:11
-1

.on adds an event listener with the defined name. Some of the events are predefined like click, onchange, onkeyup, onkeypress, onkeyrelease, etc.

But if there are native events, like .click() you should rather use it instead of .on("click").

Or in short words: There no differents, this events are just predefined and you should use the native functions for it.

In my opinion you should rather use the html-attributes. Because when your code gots bigger and bigger you would easier find it while debugging your page.

Not the answer you're looking for? Browse other questions tagged or ask your own question.