0

Context

I have a <div id='parent'> and I am changing its content using $('#parent').html('my new html text') repeatedly. Within the div I have child nodes and I attach jQuery event handlers to their click event. However after changing the children the handlers are on the old elements, so I have to attach again.

I am concerned some resource wasting effect, does the old event handlers lock any resources? (or should I unattach the handlers before I change the parent content?)

Very similar issue, but more complex: Say I utilize a jQuery plugin on the children. Normal case I write something like this:

$("<my selector which selects multiple children>").TouchSpin({
       // does not matter
    });

However after the content changes, I have to re-apply the plugin. The story is the same, do I have to concern about locked resources? If I should undo the plugin apply on the old children I do not even know how to do that.

Question

  • What is the correct way to attach event handlers on dynamically replacable dom elements?
  • What is the correct way to apply jQuery plugin on dynamically replacable dom elements?
g.pickardou
  • 32,346
  • 36
  • 123
  • 268

2 Answers2

3

You should delegate the event listener to an element that is always attached to the DOM, like #parent or document:

$('#parent').on('click', '.dynamic_attached_element', () => {
   // Handle click event on '.dynamic_attached_element'
});
kapantzak
  • 11,610
  • 4
  • 39
  • 61
  • Many thanks. Is this mean that the case of the jQuery plugin on the repeatedly replaced elements is a completely other topic? – g.pickardou Mar 07 '18 at 10:10
  • In case of jQuery plugins, you have to instanciate the plugin each time a new element is added to the DOM, except if the plugin handles this case internally – kapantzak Mar 07 '18 at 10:11
  • Maybe I am overworry the resource thing, but what will happen the disappearing dom elements having a jQuery plugin still attached on them? – g.pickardou Mar 07 '18 at 10:14
0

By using classes in your selectors you can do something like the following:

$(document).on('click', '.parent_element .child_element', function()( {
});

The above will ensure that the event will only be attached on the dynamic elements contained within the parent element.

If the parent element is always present then you can change it to:

$('#parent').on('click', '.child_element', function()( {
});
Ted
  • 3,985
  • 1
  • 20
  • 33