skyork
skyork

Reputation: 7401

Add callback to the class or individual elements

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:

  1. Add a callback to all of them statically and upfront using the class selector: $(".btnClass").on("click", function(e) { ... });
  2. Or add a callback dynamically and individually when a button is toggled visible: 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

Answers (1)

ryan
ryan

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

Related Questions