jQuery .on('click') vs. .click() and .delegate('click')
Both modes are still supported.
The following call to bind()
:
$(".foo").bind("click", function() {
// ...
});
Can be directly converted into the following call to on()
:
$(".foo").on("click", function() {
// ...
});
And the following call to delegate()
:
$("#ancestor").delegate(".foo", "click", function() {
// ...
});
Can be converted into the following call to on()
:
$("#ancestor").on("click", ".foo", function() {
// ...
});
For completeness, the following call to live()
:
$(".foo").live("click", function() {
// ...
});
Can be converted into the following call to on()
:
$(document).on("click", ".foo", function() {
// ...
});
UPDATE:
Except on
event, the rest of the events were deprecated in different jQuery versions.
bind
- version deprecated: 3.0live
- version deprecated: 1.7, removed: 1.9delegate
- version deprecated: 3.0
The on
method can replace both bind
and delegate
depending on how it's used (and also click
as bind
can replace that):
.click(handler) == .on('click', handler)
.bind('click', handler) == .on('click', handler)
.delegate('click', '#id', handler) == .on('click', '#id', handler)
Neither the click
, delegate
or bind
methods have made it to the deprecated page yet. I doubt that the click
method ever will.
You can deduce the usage for the aliases from the source code.
console.log($.fn.delegate);
function (a, b, c, d) {
return this.on(b, a, c, d);
}
console.log($.fn.bind);
function (a, b, c) {
return this.on(a, null, b, c);
}
The documentation also provides the usage examples:
$(elements).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(elements).on(events, selector, data, handler); // jQuery 1.7+