You need to delegate the event, like so:
$(document).on('click', '#button1', function(){
$("#simon .3").replaceWith(function(){
return $("<p class='3'> hello im info 2</p>");
});
Read more about event delegation here.
Question
I am trying to make a simple container where the user can click a next button to continue to see more content, and then iterate to be able to continue to see even more content. I have the jquery set up as followed, the first set works perfectly but the second doesn't:
$('#button').click(function(){
$("#simon .1").replaceWith(function(){
return $("<p class='3'>hello im info1</p>");
});
$("#button").replaceWith(function(){
return $("<p id='button1'><a href='#'>button1</a> </p>");
});
});
$('#button1').click(function(){
$("#simon .3").replaceWith(function(){
return $("<p class='3'> hello im info 2</p>");
});
$("#button1").replaceWith(function(){
return $("<p id='button2'><a href='#'>button2</a> </p>");
});
});
the html:
<p class="1"> i am info 0 </p>
<p id="button"><a href="#">button</a> </p>
thank you in advance!
Solution
You need to delegate the event, like so:
$(document).on('click', '#button1', function(){
$("#simon .3").replaceWith(function(){
return $("<p class='3'> hello im info 2</p>");
});
Read more about event delegation here.
OTHER TIPS
You need to use event delegation here to attach the click event to your newly created buttons:
$(document).on('click','#button1', function() {
$("#simon .3").replaceWith(function(){
return $("<p class='3'> hello im info 2</p>");
});
$("#button1").replaceWith(function(){
return $("<p id='button2'><a href='#'>button2</a> </p>");
});
});
Actually, we should not use $(document)
here for delegated event handling since it is much more efficient to bind them to the closest parent that is not dynamic which is the parent element of your button.