0

I've created an element that can be cloned multiple times. Each clone has a remove button that removes it from the DOM. I'm listening on a parent for the click on the cloned remove button but I only get the event for the original button. No event is detected for any other remove buttons.

To clone I use:

var $original = $(originalElementSelector);
$newCopy = $original.clone()
$original.after($newCopy);

My listener looks like this:

$(parentElement).on('click', '[data-clone-remove]', onRemoveClicked)

The original element is a descendant of the parent element. If I change it to $(document).on(... then it works but it is listening for events from the whole document which is not what I want. The listeners are attached on document ready and the parent definitely exists at that point. The first remove button that exists on page load works as expected but no others do.

Any idea where I'm going wrong?

Simon
  • 61
  • 2
  • 8

2 Answers2

0

Use $original.clone(true). It clones also the events. Source

Programmer
  • 1,973
  • 1
  • 12
  • 20
  • The event listener is not on the cloned element but on the parent. – Simon Aug 01 '18 at 13:48
  • The cloned element is also a child of that parent? It also has the attribute "data-clone-remove"? – Programmer Aug 01 '18 at 13:52
  • Yes it's exactly the same and added to the parent. I think it was the click event being interrupted by the element being removed from the DOM as I said in my answer below. – Simon Aug 01 '18 at 14:37
0

On further testing it looks like it was removing the button from the DOM that was causing the click event bubbling to fail. Dispatching a different event on remove and listening for that in the parent worked fine.

Might be related to the answers here:

If you delete a DOM element, do any events that started with that element continue to bubble?

Simon
  • 61
  • 2
  • 8