Is there any difference between the following code?
$('#whatever').on('click', function() { /* your code here */ });
and
$('#whatever').click(function() { /* your code here */ });
In click() it will be the object on which the handler is attached. In onclick() it would be a normal function call and this would be inherited from the calling context.
The difference is that the first is an event listener, and the second is an event handler content attribute.
Definition and Usage. The onclick event occurs when the user clicks on an element. In HTML: <element onclick="myScript">
off('click'). on('click',function(){}); It will simply remove any previous event handler attached to the event and create a new one. Follow this answer to receive notifications.
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.
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
.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.
.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");
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()
.
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