Event Delegation
Handle events from many children with a single listener on a parent.
Syntax
$(parent).on("event", "childSelector", handler);When events happen on a child element, they bubble up through its ancestors. Delegation uses this to attach one handler on a parent that catches events from all its children — even ones added later.
Syntax
$(parent).on("click", childSelector, handler);The second argument is a selector: the handler only runs when the event started on a matching child.
Example
Loading editorβ¦
Press Run to see the result.
When to use it
- A todo app uses event delegation on the list container to handle clicks on dynamically added todo items without re-binding.
- A data table attaches one delegated .on('click', 'tr') handler to the tbody instead of a handler per row.
- An infinite-scroll feed delegates load-more button clicks to the feed wrapper so newly injected buttons work automatically.
More examples
Handle clicks on dynamic list items
Delegating to #todos means the .del handler works for every button added in the future, not just those present at load.
<ul id="todos"></ul>
<button id="add">Add item</button>
<script>
$(function () {
var n = 0;
$("#add").on("click", function () {
n++;
$("#todos").append("<li>Task " + n + " <button class='del'>x</button></li>");
});
$("#todos").on("click", ".del", function () {
$(this).closest("li").remove();
});
});
</script>Delegate row clicks on a table
One delegated handler on tbody handles selection for every row, including rows appended later by AJAX.
<table id="grid">
<tbody>
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
</tbody>
</table>
<p id="selected"></p>
<script>
$(function () {
$("#grid tbody").on("click", "tr", function () {
$("#grid tr").removeClass("active");
$(this).addClass("active");
$("#selected").text($(this).find("td").first().text());
});
});
</script>Namespace events for safe removal
The .myFeature namespace lets you remove only this specific handler with .off() without affecting other click listeners.
<button id="toggle">Toggle listener</button>
<button id="action">Click me</button>
<p id="out"></p>
<script>
$(function () {
var active = false;
$("#toggle").on("click", function () {
if (!active) {
$("#action").on("click.myFeature", function () {
$("#out").text("Feature fired!");
});
} else {
$("#action").off("click.myFeature");
}
active = !active;
$(this).text(active ? "Disable" : "Enable");
});
});
</script>
Discussion