What is event delegation in jQuery?

jQuery Events Intermediate 1–2 Yrs2–3 Yrs Conceptual 1 min read

Quick Answer

Event delegation attaches one handler to a stable ancestor element and uses event bubbling to handle events from matching descendants — including elements added later. In jQuery it's $(parent).on('click', '.child', handler). The second selector argument is what makes it delegated.

Event delegation means instead of putting a handler on every button in a list, I put one handler on the container and let the click bubble up to it. In jQuery that's the three-argument form of on — on('click', '.row-delete', handler) on the parent. jQuery checks whether the thing that was clicked matches that selector and, if so, runs the handler with this set to that element. The big win is that it works for elements added later by AJAX, so I don't have to rebind every time I re-render the list, and it's one handler instead of hundreds.

$('.child').on('click', fn) binds directly to the elements that exist right now — new .child elements added by AJAX won't have the handler. $('#list').on('click', '.child', fn) binds to #list once; when a click bubbles up from any .child, jQuery checks the selector and runs the handler with this set to the matched child.

Benefits: works for dynamic content, one handler instead of hundreds (less memory), no need to rebind after re-rendering a list. The old .live() and .delegate() are replaced by .on() with a selector.

jQuery — delegated vs direct
// direct: only binds to rows that exist now
$('.row-delete').on('click', onDelete);

// delegated: handles current AND future .row-delete inside #grid
$('#grid').on('click', '.row-delete', function (e) {
  const id = $(this).closest('tr').data('id');
  onDelete(id);
});