Event Delegation
Bind events to a stable parent rather than individual children. Reduces the number of event listeners and works for dynamically added elements.
Bind events to a stable parent rather than individual children. Reduces the number of event listeners and works for dynamically added elements.
// BAD: 1000 event listeners for 1000 rows
$(".table tbody tr").on("click", handler);
// GOOD: 1 listener on the table body via delegation
$(".table tbody").on("click", "tr", handler);
// Also handles dynamically added rows:
$(".list").on("click", ".item", function() {
$(this).toggleClass("selected");
});
// Remove all delegated handlers when cleaning up:
$(".list").off("click", ".item");
Event delegation is not always faster for small lists — use it mainly for dynamic content and large lists.