Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using .on() or .click() to attach an event handler?

Tags:

jquery

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

?

like image 659
njr101 Avatar asked Oct 09 '22 06:10

njr101


1 Answers

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.

like image 114
Rory McCrossan Avatar answered Oct 13 '22 11:10

Rory McCrossan