Difference between .on('click') vs .click()

Is there any difference between the following code?

$('#whatever').on('click', function() {
     /* your code here */
});

and

$('#whatever').click(function() {
     /* your code here */
});

I think, the difference is in usage patterns.

I would prefer .on over .click because the former can use less memory and work for dynamically added elements.

Consider the following html:

<html>
    <button id="add">Add new</button>
    <div id="container">
        <button class="alert">alert!</button>
    </div>
</html>

where we add new buttons via

$("button#add").click(function() {
    var html = "<button class='alert'>Alert!</button>";
    $("button.alert:last").parent().append(html);
});

and want "Alert!" to show an alert. We can use either "click" or "on" for that.


When we use click
$("button.alert").click(function() {
    alert(1);
});

with the above, a separate handler gets created for every single element that matches the selector. That means

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.
When we use .on
$("div#container").on('click', 'button.alert', function() {
    alert(1);
});

with the above, a single handler for all elements that match your selector, including the ones created dynamically.


...another reason to use .on

As Adrien commented below, another reason to use .on is namespaced events.

If you add a handler with .on("click", handler) you normally remove it with .off("click", handler) which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:

$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });

with unbinding via

$("#element").off("click.someNamespace");

Difference Between IN and ON, IN vs ON. Prepositions are one of the most hated parts of speech. Even experienced writers are sometimes uncomfortable using them. Often people are  When referring to time, on is used to talk about days and dates while at is used to talk about specific times. This is the key difference between on and at. You can see the difference in usage in the following examples. The office is closed on Saturdays.

Is there any difference between the following code?

No, there is no functional difference between the two code samples in your question. .click(fn) is a "shortcut method" for .on("click", fn). From the documentation for .on():

There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

Note that .on() differs from .click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas .click() does not. When .on() is called without a selector parameter, it behaves exactly the same as .click(). If you want event delegation, use .on().

The Difference Between On and Onto, In today's Ask a Teacher, we talk about the main difference between the prepositions "on" and "onto." Here is a clue: One of them involves  The use of prepositions, both in the written word as well as verbally, can be tricky whether you are learning the English language or trying to boost your existing English grammar skills. Even very experienced writers may find themselves misusing a preposition if they aren’t paying careful attention. When it comes to in vs. on, …

.on() is the recommended way to do all your event binding as of jQuery 1.7. It rolls all the functionality of both .bind() and .live() into one function that alters behavior as you pass it different parameters.

As you have written your example, there is no difference between the two. Both bind a handler to the click event of #whatever. on() offers additional flexibility in allowing you to delegate events fired by children of #whatever to a single handler function, if you choose.

// Bind to all links inside #whatever, even new ones created later.
$('#whatever').on('click', 'a', function() { ... });

The difference between "on" and "onto" | Ask The Editor, This difference is hard to see in the examples you have asked about, because the verb, put, itself, suggests moving something from one place to another, and the  Summary: 1. IN is used when you are referring something enclosed by limitations while using IN is relatively specific and does not denote anything enclosed. 2. IN is used to denote a location of something inside a space while on generally, denotes something above a surface or within proximity. 3.

As mentioned by the other answers:

$("#whatever").click(function(){ });
// is just a shortcut for
$("#whatever").on("click", function(){ })

Noting though that .on() supports several other parameter combinations that .click() doesn't, allowing it to handle event delegation (superceding .delegate() and .live()).

(And obviously there are other similar shortcut methods for "keyup", "focus", etc.)

The reason I'm posting an extra answer is to mention what happens if you call .click() with no parameters:

$("#whatever").click();
// is a shortcut for
$("#whatever").trigger("click");

Noting that if you use .trigger() directly you can also pass extra parameters or a jQuery event object, which you can't do with .click().

I also wanted to mention that if you look at the jQuery source code (in jquery-1.7.1.js) you'll see that internally the .click() (or .keyup(), etc.) function will actually call .on() or .trigger(). Obviously this means you can be assured that they really do have the same result, but it also means that using .click() has a tiny bit more overhead - not anything to worry or even think about in most circumstances, but theoretically it might matter in extraordinary circumstances.

EDIT: Finally, note that .on() allows you to bind several events to the same function in one line, e.g.:

$("#whatever").on("click keypress focus", function(){});

Difference Between In and On (with Comparison Chart), If you are speaking literally, "in" usually carries the meaning of "surrounded by", or "completely enclosed": "There's a fly in my soup." "The dog is  As prepositions of time, in is used with unspecific times, days, months and years whereas on is used with specific days and dates. As prepositions of place, in indicates that something is within the boundaries of an area or is contained within something else while on indicates something is at the surface of something.

No, there isn't. The point of on() is its other overloads, and the ability to handle events that don't have shortcut methods.

Difference between IN, ON and AT, Can you please explain the differences between on, over, and above? Thanks. Without the context that these words are used in, I will assume that they are most probably being used as propositions of position because that is the most common use.

English Grammar: Prepositions: Difference between IN and ON , Well, put away your dice and let's learn the difference between those three words​. -X!- I find it helpful to think of the definition of these prepositions  what is the difference between the following sentence: 1, He is in a meeting. 2, He is at a meeting. 3, He is on a meeting. I have found that the difference between first 2 sentences is in a meeting implies being on the same premises as the speaker, but at a meeting implies being on a different premises than the speaker..

What is the difference between ”in” and ”on”?, Evalyn Tran. Answered Mar 9, 2016. You should explain them together with place and time. For PLACE: On means 'in contact with a surface' or 'touching', as in " There is a glass on the table. ", " There is a picture on the wall. ", " I see a fly on the ceiling. ", and " I'm standing on top of the mountain. ".

What's the Difference between On, Over, and Above?, Metaphorically, in is used for months and years, on is used for specific dates. And likewise, in is used for a city, country, or state, on is used for a street, at for the exact number. I live in Torrance, CA, on 160th Street, at 2500 160th Street. In the USA.

Comments
  • What about: $('button.alert').on('click', function() { alert(1); }); ?
  • @andreister : correct me if I'm wrong but I believe that another advantage is the usage of namespaces when using on('click' ...), see stackoverflow.com/a/3973060/759452 ie. on('click.darkenallothersections' ...) and at the same time have on('click.displaynextstep' ...) , then I can unbind only the one I choose using .unbind('click.displaynextstep')
  • I don't think that a separate handler is created for every element that matches the selector. I think that 1 handler would be created, but that the overhead comes from binding this handler to multiple elements and monitoring all these elements. At least, I didn't find this in the documentation.
  • Can anyone explain why .on can work for dynamically added item but .click cannot?
  • on() is the trend in jQuery. I had to update $(window).load(function() {}); to $(window).on("load", function (e) {}) when I upgraded to jQuery 3.
  • what about the performance issue pointed out my @andreister ?
  • @rubo77 negligible at best. We're taking single-figure milliseconds.
  • @RoryMcCrossan that's a big deal for me though - I am looking for this because i have up to 3000 questions on a page that need events. One milisec each makes my page take 3 seconds longer to perform. Your comment isn't helpful for big lists.
  • The bigger issue is why you have 3000 questions on a page. If you follow good UI patterns you should never have that much information on a page. Look into paging, or lazy loading. Even using event delegation to have a single event handler for all those elements would be better.
  • @rubo77 - The performance gain is only seen when using event delegation by passing a selector parameter. If you call .on() without a selector parameter there is no performance improvement over using .click().
  • "Bind to all links inside #whatever, even new ones created later." Isn't that exactly what .live() does? Also, this seems to contradict with the other answers which say that it only has the functionality of .click(), and therefore doesn't apply to future events.
  • @babonk - This doesn't contradict the other answers, because as Interrobang said in the first paragraph .on() can do what .click() does and do what .bind() and .live() do - it depends what parameters you call it with. (Some other answers mentioned this too.) Note though that "Bind to all links inside #whatever" is not what .live() does, it's what .delegate() does. .live() binds to all inside document rather than letting you specify the container. Note also .live() is deprecated from jQuery 1.7 onwards.
  • +1 for delegated events: "By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers." api.jquery.com/on
  • Aren't the methods both loaded in memory to use ? So it doesn't matter ? And for readability it's maybe handier ?