5

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() { ... });

?

1
  • You don't have to worry about legacy code, it's highly unlikely they're gonna remove the click shorthand completely. The .on() handler is just a more efficient way of attaching event handlers, from being able to attach multiple event-handlers at the same time, to adding extra information to a mapped event! Commented Dec 9, 2011 at 11:55

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The docs state that .click() is converted to .bind(), not to .on(). That's why I'm confused.
In 1.7+ click() is converted to on(). I guess they havent updated the docs yet.
Thanks for the answer clear Rory. I looked through the JQuery 1.7 source to confirm - not that I don't trust you ;) The .click() call is in fact converted to .bind() as the docs say. But .bind() is in turn converted to .on(). So yes, you're absolutely right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.