Reputation: 3033
What is different between two below statement in jQuery:
1) with .bind
$("#username").bind('click',function(){
//@todo
});
2) without .bind()
$("#username").click(function(){
//@todo
});
So, when I need to use one of them?
Upvotes: 11
Views: 6542
Reputation: 103
Using .click() the function is not triggered when touching an anchor using Safari browser in an iPhone with IOS 4x. It does with bind('click')
Upvotes: 0
Reputation: 166071
There is no difference. If you read the docs for .click
you will notice the following line:
This method is a shortcut for .bind('click', handler)
You can confirm this by taking a quick look at the jQuery source:
function (data, fn) {
if (fn == null) {
fn = data;
data = null;
}
//Notice the call to bind on the following line...
return arguments.length > 0 ? this.bind(name, data, fn) : this.trigger(name);
}
I tend to use .click
over .bind
, simply because it's quicker to write. However, .bind
can be used to attach the same listener to multiple events so it's useful in that case:
$("#something").bind("click mouseover", function() {
//Do stuff
});
To expand upon the comment by @Tomalak, .bind
is also useful when working with custom events. For pretty much any other event, there is a shortcut method just like .click
. The jQuery source is as follows:
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
/*Call .bind for the respective event. There is a shortcut method
for each of the events listed above*/
});
Upvotes: 23
Reputation: 99929
There is not difference, .click
is a shortcut for .bind('click',
.
.click()
called without argument is a shortcut for .trigger('click'
.
Upvotes: 3
Reputation: 50982
It is just a shortcut. There is really NO difference between them
This method is a shortcut for .bind('click', handler) in the first two variations, and .trigger('click') in the third.
Upvotes: 0
Reputation: 755587
In this form there is no difference. The click
method is just a shortcut for bind('click', ...)
. Which to use is purely a matter of preference / style
Upvotes: 2