user3502952 user3502952 - 23 days ago 8
jQuery Question

jquery append and not being able to click the appended class

I have a div which when click a new div is appened - when this new div is shown and wants to be closed by clicking on it, it does fire.

This is my fiddle

https://jsfiddle.net/foba81eb/

$(document).ready(function() {
var counter = 0;
$('.one').click(function() {
if (counter <= 0) {
$('p').append("<p id='closingCross'>X</p>");
counter++;
}
});
$('#closingCross').click(function() {
//This is not firing?!
alert("hello");
});
});


I just want it to close on click but it is doing nothing?

What am I doing wrong here?

Cheers,

Ben.

P.S - have a look at the updated fiddle

https://jsfiddle.net/foba81eb/4/

when I .hide() and then click to get it back it doesn't work!!

Answer Source

HTML:

<div class="one">
<p>
hello world
</p>
<p id='closingCross' style="display:none">X</p>

</div>

JS:

$(document).ready(function(){


var counter=0;

$('.one').click(function() {
if(counter <= 0){
  $('p').show();
  counter++;
}
 });

$('#closingCross').click(function() {
    alert("hello");
 });


});