Wednesday, 2 October 2013

Event bound to document fragment doesn't work after reappending

Event bound to document fragment doesn't work after reappending

I have a document fragment which is created like this:
var element = $("<div/>", {
class: "test"
});
Then I bind a click event on it and add it to the DOM:
element.click(function () {alert("click event successfully recognized");});
$("body").append(element);
This works perfectly so far. You may try this Live DEMO
Note: Please spare me your comments about the deprecated usage of alert()
for debugging.
The problem: Imagine all elements contained by body need to be removed to
display something else. But when this other displayed thing is not needed
anymore and the element is added to the DOM again the bound events won't
work anymore.
Like this:
$("body").empty();
$("body").append(element);
Live DEMO
Please respect that hiding the element instead of removing them is not an
option. I primarily would appreciate a detailed explanation of why this
happens and how this could be solved. I would prefer to not bind the event
again.

No comments:

Post a Comment