0

I've been using the latter of the below functions pretty much ever since .on() was added, but I've noticed recently that quite a lot of answers use the former.

What is the difference between:

$(ancestor).on(event, element, function() { ... })

And:

$(element).on(event, function() { ... })

JSFiddle example.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • 1
    http://api.jquery.com/on – Kevin B Mar 28 '13 at 14:26
  • 1
    possible duplicate of [Difference between jQuery \`click\`, \`bind\`, \`live\`, \`delegate\`, \`trigger\` and \`on\` functions (with an example)?](http://stackoverflow.com/questions/2954932/difference-between-jquery-click-bind-live-delegate-trigger-and-on) – Kevin B Mar 28 '13 at 14:28

2 Answers2

4

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.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

To me your first one:

$(ancestor).on(event, element, function() { ... })

is used when some elements have been loaded or created dynamically. Direct binding of events on those wont work, so event delegation to its closest parent element is required which was availble at the time of page load $(document) is one of those which is always available to delegate the event.

Your second one:

$(element).on(event, function() { ... })

This is a direct binding of event on element but this will work on elements which were present at the time of page load.

Jai
  • 74,255
  • 12
  • 74
  • 103