What is difference between $(".anything").click() and $(".anything").bind(click)
$(".anything").click(function() {
});
$(".anything").bind('click', function() {
});
What is difference between $(".anything").click() and $(".anything").bind(click)
$(".anything").click(function() {
});
$(".anything").bind('click', function() {
});
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.
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() {
});
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
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:
var fn = function() { alert('foo'); } $('#foo').bind('click', fn); ... $('#foo').unbind('click', fn);