Search code examples
javascriptjqueryevent-delegation

Performance overhead of event listeners on CSS classes used in JQuery code


If my markup looks like this:

<button id="button-1" class="nice">
<button id="button-2" class="nice">
<button id="button-3" class="nice">

and I define the following jQuery:

$(".nice").click(function () { 
    // something happens
});
  1. How many event listeners are established? 1 or 3?

  2. If I have 1000 buttons instead of 3, should I use event delegation instead?

  3. Is it best, performance-wise, to not define jQuery calls on classes of elements if those classes contain a large number of elements in the markup?


Solution

  • 1) 3 event listeners all pointing to the same function.

    2) That depends on what you're trying to accomplish

    3) Try doing some benchmarks, see where the performance hit becomes noticeable. I've had up to 1000 elements being selected then animated at the same time - and (in FF) the performance hit was unnoticeable up until about 600-700 elements. Performance of course depends on browser and JS engine. Some (Chrome) will be faster than others (IE). Its worth mentioning that for that site I used the same method as you have in your question.