The first example delegates the event handler higher up the DOM tree. This means it can be attached to an element (ancestor
) that is in the DOM, but apply to descendants (element
) that may not yet be in the DOM.
The second example attaches the event handler directly to element
, meaning that element must exist in the DOM at the time the code runs.
Delegation has the added advantage of efficiency. Imagine you want to bind an event handler to every li
element in a large list. It's far more efficient to bind a single handler to the parent ul
, delegated to li
elements, than it is to bind many copies of the same function.
Delegation works because most DOM events bubble up the tree from the element on which they originate (the target). Following the li
example mentioned previously, consider the following code:
$("#myList").on("click", "li", function () { /* Do stuff */ });
When an descendant of #myList
is clicked, a click
event will be generated and will bubble up from that element to #myList
(this is a slight simplification - there is another phase to events called "capture" but that's not important here). The event handler bound to #myList
will be triggered, and jQuery checks to see if the target element matches the selector. If it does, it executes the handler.