11

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?

Tomalak
  • 332,285
  • 67
  • 532
  • 628
vietean
  • 2,975
  • 9
  • 40
  • 65

5 Answers5

23

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*/
});
James Allardice
  • 164,175
  • 21
  • 332
  • 312
3

There is not difference, .click is a shortcut for .bind('click',.

.click() called without argument is a shortcut for .trigger('click'.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
2

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

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

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')

0

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.

http://api.jquery.com/click/

genesis
  • 50,477
  • 20
  • 96
  • 125