jQuery interview question · Most asked

What is event delegation, and why is it useful?

Summary

Event delegation attaches one handler to a parent element and lets events from children bubble up to it; jQuery's .on(event, selector, handler) runs the handler only when the event came from an element matching the selector. It works for elements added later and uses far fewer handlers than binding to every child.

Longer Answer

// Works for rows added after this line runs, with a single handler
$("#orders").on("click", ".delete-order", function (e) {
  e.preventDefault();
  const id = $(this).data("id");
  deleteOrder(id);
});

Inside the handler, this is the matched child element, not the parent. Delegate to the closest stable container rather than document (bubbling all the way up costs time on every event and makes behaviour hard to trace). Events that do not bubble (such as focus; use focusin) need care.

Key Points

  • One handler on a parent.
  • Works for future elements.
  • this = matched child.
  • Delegate to the nearest stable container.

Deep dive: Code Clinic: review a jQuery shopping cart script

More most-asked jQuery questions

← All jQuery questions