The performance of using delegated events will not always necessarily be better than directly attaching events.
Consider the following markup:
<div id="someId">
<div class="someParent">
<div class="someElement"></div>
</div>
<div class="someParent">
<div class="someElement"></div>
</div>
<div class="someParent">
<div class="someElement"></div>
</div>
</div>
There'd be no point in attaching handlers to someParent
, delegating someElement
, as you'd be attaching the same number of handlers if you attached the handler to someElement
directly:
$('div.someParent').on('click', 'div.someElement', function() {
// given the example markup, this would be slightly slower than
// attaching the element directly $('div.someElement').on('click', ..
// as you are attaching the same number of handlers, but have the overhead
// of filtering for descendents with the class `div.someElement`
});
If the markup looked like this:
<div id="someId">
<div class="someParent">
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
</div>
<div class="someParent">
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
</div>
<div class="someParent">
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
<div class="someElement"></div>
</div>
</div>
.. and you delegated the handler like above, you'd be attaching 3 handlers, as opposed to 15 (if you'd attached the handler directly), which would perform better.
In either case, the best way would be to use the closest parent element with an id
, so you're only attaching a single handler:
$('#someId').on('click', 'div.someElement', function() {
// do some stuff
});
The other benefit of delegating handlers (as you already know), is that it will be triggered for dynamically added elements.