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?
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*/
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With