views:

80

answers:

4

What is difference between $(".anything").click() and $(".anything").bind(click)

$(".anything").click(function() {

});

$(".anything").bind('click', function() {

});
+7  A: 

Nothing, click(function() { }) is just a shortcut for bind("click", function() { }).

From the jQuery docs:

The jQuery library provides shortcut methods for binding the standard event types, such as .click() for .bind('click').

You can read more about bind() here.

Cory Larson
+4  A: 

The first is a shortcut of the second. The second is actually wrong, click should have been quoted. Further, in the second you have the added benefit that you can bind the same function to multiple events, each separated by a space. E.g.

$(".anything").bind("click keypress blur", function() {

});
BalusC
+3  A: 

In that specific case, absolutely nothing.

However:

A) If you give .click() no argument, it triggers the event instead of setting the handler.

B) only .bind() lets you use the "namespaced" way of registering handlers:

$(whatever).bind('click.myEvent', function (e) { ... });
$(whatever).unbind('click.myEvent'); // Removes just that handler
hobbs
+1  A: 

See this post, which points to the JQuery source to show that .click(fn) just calls .bind('click', fn): http://stackoverflow.com/questions/518762/jquery-clickfn-vs-bindclick-fn/518773#518773

I usually only use the latter if:

  • I want to bind multiple things, i.e. .bind('click focus', fn)
  • Just to maintain convention if I call unbind later, i.e.:
var fn = function() { alert('foo'); }
$('#foo').bind('click', fn);

...

$('#foo').unbind('click', fn);
David