Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 56 ยท Events

Event Delegation

Use delegated .on(event, selector, handler) to handle clicks on dynamic elements, keep memory low, and avoid pitfalls with focus and mouseenter.

Imagine a list with 5,000 rows, each with a delete button. Attaching 5,000 handlers is wasteful, and it still would not work for rows you add later, because a handler only attaches to elements that exist at the moment you call .on(). Event delegation solves both problems with one trick: put a single handler on a stable ancestor and let events bubble up to it.

This lesson builds on Handling Events. You need to know what event.target and event.currentTarget are, because delegation is built on that difference.

How delegation works

Most events bubble: they fire on the element that was hit, then on its parent, then on the grandparent, up to the document. A delegated handler listens at an ancestor, checks whether the original target (or one of its ancestors up to the listener) matches a selector, and only then runs your function.

flowchart TD
  A["click on a delete button"] --> B["li.row"]
  B --> C["ul#list (delegated handler lives here)"]
  C --> D{"Does the target match button.delete?"}
  D -->|yes| E["Run the handler with this = the button"]
  D -->|no| F["Ignore"]

The click travels upward; the handler on the list checks each hop against the selector.

The syntax adds a selector as the second argument:

JavaScript
$("#list").on("click", "button.delete", function (event) {
  $(this).closest("li").remove();
});

Notice what this is: inside a delegated handler, this is the matching element (the button), not the element holding the handler (the list). event.currentTarget is also the button here, while event.delegateTarget is the list. This is the one place where currentTarget and the handler's owner differ.

Direct versus delegated

Direct One handler per element. Needs the element to exist.
Delegated One handler on an ancestor. Works for future elements.
1 / 2

Handling elements that do not exist yet

Here is the classic failure and its fix, side by side. In the demo, the first button list uses direct handlers and the second uses delegation. Add items to both and click them.

Direct versus delegated handlers

Click "Existing item" in both lists: both toggle. Add items and click them. Only the delegated list reacts, because the direct handler was attached once, to the one li that existed back then.

The older .live() method was removed in jQuery 1.9 and .delegate() is deprecated since jQuery 3 (see What changed in jQuery 3). Delegated .on() is the replacement for both.

Choosing the ancestor

The ancestor must be a stable element that exists when you bind and does not get replaced later. Good choices are the closest container that never changes, such as the <ul> or <table> itself. Avoid binding on document or body for everything:

  • Every matching event in the whole page is tested against your selector.
  • It becomes hard to see who owns which behavior.
  • If anything calls stopPropagation() on the way up, your handler never runs.
JavaScript
// Hard to maintain and does more work than needed
$(document).on("click", ".delete", handler);

// Better: the nearest stable container
$("#cart").on("click", ".delete", handler);

Clicks on child elements of the match

When the selector matches a button that contains an icon, a click on the icon still triggers the handler, and this is the button. That is usually what you want. Compare event.target, which would be the icon:

JavaScript
$("#toolbar").on("click", "button", function (event) {
  console.log(this.nodeName);          // BUTTON
  console.log(event.target.nodeName);  // maybe SVG or SPAN
});

Use this or $(event.target).closest("button") when you need the button; never assume event.target is the element you matched.

Pitfalls

Events that do not bubble. focus and blur do not bubble, and neither do mouseenter and mouseleave. jQuery quietly maps delegated focus and blur onto their bubbling cousins, but that mapping is a detail you should not rely on: with plain JavaScript listeners, or in code you later migrate, delegated focus silently never fires. Say what you mean and use the bubbling events:

Do not delegate Delegate this instead
focus focusin
blur focusout

mouseenter and mouseleave do not bubble natively either, but jQuery simulates them from mouseover and mouseout, so a delegated mouseenter works in jQuery. The focus/blur rule is the important one.

Stopped propagation. If a handler between the target and your ancestor calls event.stopPropagation(), the event never reaches the delegated handler. Return to Controlling Events before sprinkling return false through your code.

Expensive selectors. The selector runs on every event that reaches the ancestor, so keep it simple: a class or tag, not a long filter expression.

Fast-firing events. Delegating mousemove or scroll on a big container runs the check constantly. These events rarely need delegation anyway.

Delegating focus with focusin

The form has one handler for each direction, no matter how many inputs you add later.

When delegation is not worth it

For a single button or a handful of static elements, a direct handler is simpler and perfectly fast. Delegation pays off when there are many targets, when the targets are created dynamically, or when you want one place to remove all behavior. Choose by need, not by habit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a delegated handler work for elements added after the page loads?

    Only the ancestor holds the handler. Because events bubble, new children are covered automatically.
  2. 2. Inside $("#list").on("click", "li", fn), what is this?

    In a delegated handler this is the element that matched the selector. event.delegateTarget is the element the handler was bound to.
  3. 3. Which event should you delegate to react to a field gaining focus?

    focus does not bubble, so delegating it relies on a jQuery workaround that plain JavaScript does not have. focusin bubbles and fires at the same moment.
  4. 4. Why is $(document).on("click", ".item", fn) often a poor default?

    Binding on the nearest stable container does less work and keeps ownership clear.

Summary

  • Delegation is .on(event, selector, handler) bound on a stable ancestor.
  • Events bubble up, and jQuery runs the handler only when the target matches the selector.
  • In delegated handlers this is the matching element and event.delegateTarget is the ancestor.
  • It saves memory and works for elements added later.
  • Use focusin/focusout instead of non-bubbling focus/blur.
  • Bind on the nearest stable container, not on document by default.

Next, learn to cancel default behavior, stop bubbling and trigger events yourself in The Event Object and Controlling Events.