When I replaceWith
an element to bring one out of the DOM, then replaceWith
it back in, events registered to it do not fire. I need to events to remain intact.
Here's my Javascript:
var replacement = $(document.createElement('span'));
var original = $(this).replaceWith(replacement);
replacement
.css('background-color', 'green')
.text('replacement for ' + $(this).text())
.click(function() {
replacement.replaceWith(original);
});
In the demo, when you click an element, it is replaced with another element using replaceWith
. When you click the new element, that is replaced with the original element using replaceWith
. However, the click handler does not work any more (where I would think it should).
$.fn.live
didn't work because I was dealing with actual elements, not a selector. ($.fn.delegate
(which didn't exist then) may work for you as alive
alternative.) Because of the answer I selected, I assume I did end up re-attaching the event handler. You may try deep cloning the element as well (which IIRC may keep event handlers in the latest jQuery). – Pandolfi