Assuming I just want to attach a simple click handler to an element, I've always done this:
$("#mydiv").click(function() { ... });
Looking at the JQuery docs, it seems that .on()
is the "recommended" way to attach event handlers and replaces .bind()
, .delegate()
and .live()
:
As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live().
And in the docs for .click()
it says:
This method is a shortcut for .bind('click', handler) in the first two variations, and .trigger('click') in the third.
So this implies that .click()
is using .bind()
which will be deprecated and replaced by .on()
, right? Or is the implication that .click()
will stick around, but it will at some point become a shortcut for .on("click")
?
Basically, my question is this... When writing JQuery code today, should I use:
Variant 1: $("#mydiv").click(function() { ... });
or:
Variant 2: $("#mydiv").on("click", function() { ... });
?
Personally I would use on()
for all event bindings from jQuery 1.7+.
It means there's no ambiguity between elements which are added dynamically and those available on page load.
Also, as you state, click()
(and other event shortcuts) are converted to on("event", function() { ... });
by jQuery anyway, so it saves a step in the process - not that this makes a noticeable difference of course.
And finally, on("click")
reads better in my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With