0

When I click a div, I append (under some conditions) another div to the document via jQuery. I would like to create a click listener to this new div. Here is the code and fiddle:

<div class="test">click me!</div>

<script type="text/javascript">
$('.test').click(function() 
{
    $(document.body).append('<div class="close">close</div>');
});

$('.close').click(function() 
{
    $('.test').hide();
    alert('close clicked');
});

</script>

My goal is to register a click listener to close div, to handle future clicks, but it seems it doesn't work if the div is not created yet. How can I do? I would like to avoid to register a click listener after each close creation. Thanks in advance.

Giorgio
  • 1,800
  • 5
  • 32
  • 56

1 Answers1

2

Use event delegation using on(), it will make event work on dynamically added html:

$(document).on('click','.close',function() 
{
    $('.test').hide();
    alert('close clicked');
});

UPDATED FIDDLE

Ehsan Sajjad
  • 59,154
  • 14
  • 90
  • 146