0

Binding events to a dynamically created element that has a static ancestor is fairly easy using jQuery, as demonstrated in this answer:

$(staticAncestors).on(eventName, dynamicChild, function() {});

But what if the dynamicChild is of a dynamicAncestor? Is there any way to make the following work:

$(dynamicAncestors).on(eventName, dynamicChild, function() {});
Community
  • 1
  • 1
Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57

2 Answers2

2

When using on, you should bind to the nearest static parent element. In some cases, that may be body:

$('body').on(eventName, 'dynamic-element', function() {  });

Binding all events to body is generally bad practice though, so it's difficult to answer your question more thoroughly without seeing your DOM. But binding to the nearest static parent will work for what you're trying to achieve.

BenM
  • 52,573
  • 26
  • 113
  • 168
1

If dynamicAncestors is a selector, no. The element must exist when you bind the event handler. This is the key point of event delegation: using a static parent as a middleware for listening to events of (dynamically generated) descendants. You are probably looking for the following syntax:

$('staticParentOfdynamicAncestors').on(
   eventName, 
  'dynamicAncestors dynmaicChild', 
  function() {}
);

Check Understanding Event Delegation.

Ram
  • 143,282
  • 16
  • 168
  • 197