jQuery clone() not cloning event bindings, even with on()
I think you should use this overload of the .clone() method:
$element.clone(true, true);
clone( [withDataAndEvents] [, deepWithDataAndEvents] )
withDataAndEvents: A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false.
deepWithDataAndEvents: A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).
Beware that .on()
does not actually bind the events to the targets but to the element you are delegating to. So if you have:
$('#container').on('click', '.button', ...);
The events are actually binded to #container
. When a click on a .button
element occurs, it bubbles up to the #container
element The element which triggered the event is evaluated upon the selector parameter of .on()
and if it matches, the event handler is executed. This is how event delegation works.
If you clone the element #container, you have to deep clone with events and data for the bindings made with .on()
to be preserved.
This would not be necessary if you were using .on()
on a parent of #container
.