jquery – Is there any difference between codes A and B below?

Question:

Code A

$('#tantoFaz').on('click', function() {
 /* ....... */
});

Code B

$('#tantoFaz').click(function() {
 /* ....... */
});

Answer:

As presented, there is no difference. In fact, the click function itself can be thought of as a shortcut to the on function, with the click parameter, with some caveats. The click function has three variations:

.click(handler)

Where handler is a function that is executed at each click event of the element. This variation is analogous to using .on("click", handler) , as asked.

.click(eventData, handler)

The second variation takes an eventData parameter. The functioning of this variation is also analogous to the use of the on function, although the data informed in eventData will be passed as a parameter to the handler when the event is triggered.

.click()

The third variation, without parameters, is the one that must be taken care of in this comparison, as its use is not similar to the on function. What it does, in fact, is to trigger the click event of the element in question, executing all the functions defined by the previous variations. This variation is analogous to .trigger("click") .

So there is no difference between the codes presented in the question.

Reference: Official documentation

Scroll to Top