Tuesday 11 June 2019

jquery - Difference between delegating events to different elements in the DOM




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
}


...








Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...