Reputation: 69
Is there any difference between this two syntaxes from a performance point of view or it doesn't matter which one I will use?
$(document).on('click', '#button', function () {
//some code
});
and
$('#button').on('click', function () {
//some code
});
Upvotes: 0
Views: 20
Reputation: 700212
Yes, there is a difference in performance, and also in function.
The first way (delegated events) will bind one event on the document element, that will catch any click that bubbles up to it, and check if the target element matches the selector #button
.
The second way (direct events) will bind one event on every element that matches the selector #button
.
(In the specific case of the selector #button
there will of course not be more than one element.)
Delegated events are mainly used if you add elements later that would match the selector, and when you want the event to be handled for those elements also without having to bind it again.
You should be a bit careful when you use delegated events. As the event will catch every click that happens in the scope and evaluate the selector every time, there is a bit of overhead for every click. If you bind several events this way, there would be a bunch of selectors that needs to be evaluated on every click.
Upvotes: 1