Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .bind('click') and .click() in jQuery?

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?

like image 348
vietean Avatar asked Sep 19 '11 16:09

vietean


1 Answers

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*/
});
like image 113
James Allardice Avatar answered Sep 18 '22 12:09

James Allardice