I ran into an interesting problem. On my site, i swap out content dynamically when hovering over a certain link. This is accomplished by something similar to:
$('#box').html($('#newcontent').html());
Now inside this #newcontent part, there is a <button>-Element to which I assigned a click event like this: (inside the $(document).ready()-function)
$("button#buttonName").click(function(){
$("div#containerName").toggleClass("hidden");
}
hidden is a css-Class doing the display:none magic. The container #containerName is outside both the element containing the button and the element containing the structure that is being changed with html().
Mockup of the structure at this point
<div id="somethingthatwhenhoveredoverwillswapthecontent">Hover over me!</div>
<div id="box">Change me!</div>
<div id="newcontent" class="hidden">I am renewed!
<button id="buttonName">Show the weird box at the bottom</button>
</div>
<div id="containerName" class="hidden">
I am content that is only shown when the button is clicked
</div>
So what happens is this: the page is loaded, the content swapping script works fine, but the button will not fire it’s click event, which for testing reasons didn’t even give an alert('whatever');. It looks like once the html() swaps the content from the <div id="newcontent"> to the <div id="box">, the event gets unbound (I suspect).
Is this just me not grasping a concept or is the whole approach done wrong?
Behind the scenes jQuery is creating a new DOM element, rather than making a ‘copy’ of the original. Because of this it doesn’t have the event handler of the original. You can either manually re-assign the handlers along with your
html()call, or you can usedelegate()to add the event, like this: