Reputation: 7401
I use JQuery, and I have a collection of buttons all of which have class btnClass
. Some (or all) of them are toggled visible/invisible repeatedly based on some changing condition.
I want to add a callback to the click event when any of these buttons are clicked. I have two options:
$(".btnClass").on("click", function(e) { ... });
btn.toggle(true).on("click", function(e) { ... });
Performance wise, which is better and why? Is there some other approach that is better than both?
Upvotes: 0
Views: 118
Reputation: 6655
Performance wise, use event delegation. It will have loads better performance compared to either of those options because a single handler is only attached once, on a known and existing parent element.
Similar to the example provided in the .on()
documentation:
$("#wrapper").on("click", ".btnClass:visible", function(event){
alert($(this).text());
});
Upvotes: 3