On page load I bind Event Handlers with content which is hidden on at the time of page load.
If users clicks on the button, the hidden content is pulled and replaces the main content of the page, Now the event Handlers which were initially binded do not work.
HTML code on Page load
<p> Initial content of the page </p>
<button id="button"> Click Here to change content</button>
<div class="show-later" style="display: none;"> Some Hidden content </div>
After the user clicks a button the new dom looks some thing like this
<p>
<div>Some Hidden content</div>
</p>
After the manipulation the event handlers binded to the div element do not work any more. Please notice that the div goes into the P element after DOM Manipulation.
jQuery Code:
$('#button').click(function(){
var show_later = $('.show-later').html();
$('p').html(show_later);
});
$(document).ready(function(){
$('.show-later').click(function(){
// Do something.....
});
});
You’re not moving the
<div>, you’re just taking its content (a text node) and copying that to the paragraph. Contrary to what you’ve stated in the question, the resulting DOM will actually look like this:The
<div>is still there, it still has content, and it still has the event handler forclickbound to it; but it’s also still hidden, so there’s no way you can click on it.I’d suggest that you actually move the
<div>into the<p>element, like so:That will select the
<div>, make it visible, and then move the element itself into the<p>.