Event handlers, connected directly to DOM elements, die when the DOM elements are removed from the DOM.
Replacing the content is enough.
Delegated events as a better alternative:
The rules for deferred events (event delegation) are different, as the events are not actually connected to the individual DOM elements, but are captured at a higher level (like the document
). A selector is then run and the event function run against the matching element(s). Deferred events tie up less memory but are a tiny(-tiny) bit slower to run (you will never notice the difference for mouse events) as the element search is only done when the event triggers.
I would generally recommend using deferred on
, instead of connecting to lots of individual elements, especially when your DOM elements are loaded dynamically.
e.g.
$(document).on('someeventname', 'somejQueryselector', function(e){
// Handle the event here
});
Sequence of events with a delegated handler
- Attach a delegated handler to a single non-changing ancestor element (
document
is the best default for several reasons if nothing else is closer/convenient). See notes for details.
- The chosen event bubbles up to the delegated target element
- The jQuery selector is applied to just the elements in the bubble-chain
- The event handler is run against only the matching elements that caused the event.
The upshot of this is that delegated handlers only match at event time, so can cope with dynamically added/removed content. The runtime overhead is actually lower at event registration (as it only connects to a single element) and the speed difference at event time is negligible (unless you can click a mouse 50,000 times per second!).
Notes:
- With delegated events, you should try to attach them to a single element, that is an ancestor of the target elements and that will not change.
- The fallbacks are usually
body
or document
if nothing else is handy.
- Using
body
for delegated events can cause a bug to do with styling. This can mean mouse events do not bubble to body (if the computed height of body
is 0). document
is safer as it is not affected by styling.
- Also
document
always exists, so you can attached delegated event handlers outside of a DOM-ready handler with no problems.