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
});
How many event listeners are established? 1 or 3?
If I have 1000 buttons instead of 3, should I use event delegation instead?
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?
The results One <div> has 100 click handlers, and the click event is triggered by plain JS. This is interesting: When using native events, the number of listeners seems to degrade the performance faster than using jQuery.
Event listeners are among the most frequently used JavaScript structures in web design. They allow us to add interactive functionality to HTML elements by “listening” to different events that take place on the page, such as when the user clicks a button, presses a key, or when an element loads.
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With