Is there any difference between the following code?
$('#whatever').on('click', function() {
/* your code here */
});
and
$('#whatever').click(function() {
/* your code here */
});
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think, the difference is in usage patterns.
I would prefer
.onover.clickbecause the former can use less memory and work for dynamically added elements.Consider the following html:
where we add new buttons via
and want “Alert!” to show an alert. We can use either “click” or “on” for that.
When we use
clickwith the above, a separate handler gets created for every single element that matches the selector. That means
When we use
.onwith the above, a single handler for all elements that match your selector, including the ones created dynamically.
…another reason to use
.onAs Adrien commented below, another reason to use
.onis 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:with unbinding via