AllThingsSmitty/jquery-tips-everyone-should-know

Re-attach events when the DOM reloads. EG: on ajax pagination

leroy0211 opened this issue · 1 comments

When you load content through ajax (or pjax), and events are registered on elements inside that content. The events registered are not handled anymore. Because the previous DOM elements are 'destroyed'. The events should be re-attached on the DOM elements. A best practice is to attach the events on a global DOM element.
For Example:

<div id="content">
   <!-- this content will be changed with ajax //-->
</div>

Instead of attaching the events on the elements within the content, attach the events on the DOM element which will NOT be loaded or changed through ajax (in this case: #content, or sometimes: body).

$('#content').on('click', 'a', function(e){
    // here the logic when clicking on a link inside the `#content` div
});

I wouldn't necessarily say that the use of delegated events is a best practice - it very much depends on the situation. If it's a parent element that isn't too far up the DOM tree, then great. It gives you the advantage of not having to rebind events in ajax callbacks, and saves memory because you bind the event on one element rather than several.

But, a lot of people use this as a lazy solution by binding the event to the document. Relying on detecting events as they bubble up the DOM tree can cause a significant performance impact (delegated events bound to the document is what the jQuery .live function used to do, but the performance impact is why it was removed from the code base). Also, relying on these events bubbling up to the document level doesn't working on iOS. It only allows events on certain elements (namely anchors and buttons) to bubble up that far for performance reasons.

So this is a good point to make, but the performance impact needs to be considered.