Is there any difference between the following code?
$('#whatever').on('click', function() {
/* your code here */
});
and
$('#whatever').click(function() {
/* your code here */
});
Is there any difference between the following code?
$('#whatever').on('click', function() {
/* your code here */
});
and
$('#whatever').click(function() {
/* your code here */
});
They appear to be the same... Documentation from the click() function:
Documentation from the on() function:
.click
events only work when element gets rendered and are only attached to elements loaded when the DOM is ready..on
events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).As mentioned by the other answers:
Noting though that
.on()
supports several other parameter combinations that.click()
doesn't, allowing it to handle event delegation (superceding.delegate()
and.live()
).(And obviously there are other similar shortcut methods for "keyup", "focus", etc.)
The reason I'm posting an extra answer is to mention what happens if you call
.click()
with no parameters:Noting that if you use
.trigger()
directly you can also pass extra parameters or a jQuery event object, which you can't do with.click()
.I also wanted to mention that if you look at the jQuery source code (in jquery-1.7.1.js) you'll see that internally the
.click()
(or.keyup()
, etc.) function will actually call.on()
or.trigger()
. Obviously this means you can be assured that they really do have the same result, but it also means that using.click()
has a tiny bit more overhead - not anything to worry or even think about in most circumstances, but theoretically it might matter in extraordinary circumstances.EDIT: Finally, note that
.on()
allows you to bind several events to the same function in one line, e.g.:Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.
They've now deprecated click(), so best to go with on('click')
As far as ilearned from internet and some friends .on() is used when you dynamically add elements. But when i used it in a simple login page where click event should send AJAX to node.js and at return append new elements it started to call multi-AJAX calls. When i changed it to click() everything went right. Actually i did not faced with this problem before.