TExcelTAD
Home › jQuery › jQuery Event Delegation

jQuery Event Delegation

$("li").on("click", fn) attaches a handler to each <li> that exists at that moment. Items added later get no handler. Event delegation solves this — and uses less memory — by attaching one handler to a parent and letting events bubble up to it.

How bubbling works

When you click an element, the event fires on it first, then on its parent, then the grandparent, and so on up to document. A handler on the <ul> therefore "hears" clicks on every <li> inside it.

text
click on <span> inside <li>
  span → li → ul#list → body → html → document
                ▲
        one delegated handler here, filtered by "li"

The delegated form of on()

js
$(parent).on(eventName, childSelector, handler);
Part Meaning
parent An element that exists now and will contain the children (the closer, the better)
childSelector jQuery runs the handler only if the event came from (or through) a matching descendant
this inside the handler The matching child (li), not the parent

The problem and the fix

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    .col { display: inline-block; vertical-align: top; width: 46%; }
    li { cursor: pointer; padding: 2px 4px; }
    li.picked { background: #fff176; }
  </style>
</head>
<body>
  <button id="add">Add an item to both lists</button>
  <div class="col">
    <b>Direct binding</b>
    <ul id="direct"><li>Item 1</li><li>Item 2</li></ul>
  </div>
  <div class="col">
    <b>Delegated</b>
    <ul id="delegated"><li>Item 1</li><li>Item 2</li></ul>
  </div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    // ❌ direct: only the <li> elements that exist now get the handler
    $("#direct li").on("click", function () {
      $(this).toggleClass("picked");
      console.log("direct:", $(this).text());
    });

    // ✅ delegated: one handler on the <ul> covers current AND future <li>
    $("#delegated").on("click", "li", function () {
      $(this).toggleClass("picked");
      console.log("delegated:", $(this).text());
    });

    let n = 2;
    $("#add").on("click", function () {
      n++;
      $("#direct, #delegated").append($("<li>").text("Item " + n));
    });
  </script>
</body>
</html>

Add a few items, then click them: new items in the left list do nothing, while every item in the right list responds.

e.target vs this vs e.delegateTarget

With delegation, three different elements are involved:

Expression Is
e.target The innermost element actually clicked (could be a <b> inside the <li>)
this / e.currentTarget The element matching the selector (li)
e.delegateTarget The element the handler is attached to (ul)
html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    .card { border: 1px solid #ccc; border-radius: 6px; padding: 8px; margin: 4px 0; width: 280px; cursor: pointer; }
    .card button { margin-left: 8px; }
  </style>
</head>
<body>
  <div id="board">
    <div class="card"><b>Task:</b> <span>Write report</span> <button class="del">✕</button></div>
    <div class="card"><b>Task:</b> <span>Email team</span> <button class="del">✕</button></div>
  </div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#board").on("click", ".card", function (e) {
      console.log("target:", e.target.tagName,
                  "| this:", this.className,
                  "| delegateTarget:", e.delegateTarget.id);
    });

    // a more specific delegated handler for the delete buttons
    $("#board").on("click", ".del", function (e) {
      e.stopPropagation();              // don't also run the .card handler
      $(this).closest(".card").remove();
      console.log("removed; cards left:", $("#board .card").length);
    });
  </script>
</body>
</html>

Click the bold label, the text, the empty area and the ✕ button, and compare the logged values. Note that the .del handler runs before the .card handler: jQuery processes delegated handlers from the deepest matching element upward, so stopPropagation() there prevents the card handler.

When to use delegation

Use delegation when… Direct binding is fine when…
Items are added/removed dynamically (lists, tables, chat) The element is static and unique (#save-button)
There are many similar elements (a 1,000-row table) You need events that do not bubble well (mouseenter, focus — use mouseover/focusin for delegation)
HTML is replaced by AJAX (.load(), .html())

A dynamic table

Rows are created from data and replaced on every change, yet there is only one handler for all the buttons:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 13px; }
    table { border-collapse: collapse; }
    td, th { border: 1px solid #ccc; padding: 3px 8px; }
    td.qty { text-align: center; width: 40px; }
  </style>
</head>
<body>
  <table id="cart">
    <thead><tr><th>Item</th><th>Qty</th><th></th></tr></thead>
    <tbody></tbody>
  </table>
  <p>Total items: <b id="total">0</b></p>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const cart = [ { name: "Apples", qty: 3 }, { name: "Bread", qty: 1 }, { name: "Cheese", qty: 2 } ];

    function render() {
      $("#cart tbody").html($.map(cart, (item, i) =>
        $("<tr>").attr("data-index", i).append(
          $("<td>").text(item.name),
          $("<td class='qty'>").text(item.qty),
          $("<td>").append("<button data-op='inc'>+</button> <button data-op='dec'>−</button>")
        )));
      $("#total").text(cart.reduce((sum, it) => sum + it.qty, 0));
    }

    // ONE handler, survives every re-render
    $("#cart").on("click", "button", function () {
      const i = $(this).closest("tr").data("index");
      const op = $(this).data("op");
      cart[i].qty += op === "inc" ? 1 : -1;
      if (cart[i].qty <= 0) cart.splice(i, 1);
      render();
      console.log(op, "→", cart.map(it => it.name + "×" + it.qty).join(", ") || "(empty)");
    });

    render();
  </script>
</body>
</html>

Tip: Delegate to the closest stable parent (#cart), not to document. Handlers on document run for every click on the whole page, which wastes work and makes stopPropagation() in other code break them.

To remove a delegated handler, pass the same selector: $("#cart").off("click", "button").

Test yourself

Why don't items added later respond to $("li").on("click", fn)?

  1. Because click only fires once
  2. The handler was attached only to the li elements that existed at that time
  3. New elements cannot receive events
  4. Because on is deprecated

In $("#list").on("click", "li", fn), what is this inside fn?

  1. #list
  2. The matching li
  3. document
  4. The jQuery object

Which is the best element to delegate to?

  1. Always document
  2. The closest parent that exists permanently and contains the items
  3. window
  4. Each child element