1

Is there any functional or performance difference between these two jQuery change events?

$(document).on('change', '#toggleList', function () {
    //code
}

and

$('#toggleArea').on('change', '#toggleList', function () {
    //code
}

...

<div id="toggleArea">
    <select id="toggleList"></select>
</div>
noclist
  • 1,659
  • 2
  • 25
  • 66
  • 1
    only when '#toggleArea' is dynamic it make's a different. And it your opinion which way you prefer. With document you are to 100% that binding is working every time. – Sysix Dec 04 '17 at 20:55
  • 1
    unless your `#toggleArea` is the same as the document, then there would be a slight increase (like, milliseconds) in attaching the event tot he `#toggleArea`div as the event would have to propagate through fewer elements. Otherwise, none that comes to mind. – Jhecht Dec 04 '17 at 20:56

1 Answers1

3

There is no functional difference between the two. There is a (very) slight performance difference, though, as the first example requires the event to bubble up the DOM from the #toggleList element to the document. The second example needs only go as far up the DOM as the #toggleArea, so will be slightly faster.

The old live() method used to use the first method you outlined and was deprecated because of it.

In an ideal world, the delegated event should be assigned to the nearest parent element to those being dynamically created which is available in the DOM when document.ready fires. Avoid assigning it to document where possible.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339