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

click, jquery

Solution

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

- many matching elements would create many identical handlers and thus increase memory footprint

- 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");

Problem

Is there any difference between the following code? ``` $('#whatever').on('click', function() { /* your code here */ }); ``` and ``` $('#whatever').click(function() { /* your code here */ }); ```

Original source

Related problems