13

I'm trying to append new DOM objects to some Div and it works, but somehow - the events that I programmed for these new appended objects do not respond. Why is that?

I attach here a simple example: upon click on any paragraph the paragraph should hide. Yet, for paragraph that were added using .append, it doesn't work.

http://jsfiddle.net/xV3HN/

There's my code:

$(document).ready(function(){

$("#add").click(function(){
     $("#containerDiv").append("<p> I should hide as well if you click me </p>");
  });

 $("p").click(function(){
     $(this).hide();
  });

});
user3371458
  • 133
  • 1
  • 1
  • 4
  • Take a look at Event Delegation https://learn.jquery.com/events/event-delegation/ – Moob Mar 02 '14 at 19:09
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Mar 02 '14 at 19:15
  • and [Event binding on dynamically created elements?](http://stackoverflow.com/q/203198/218196) – Felix Kling Mar 02 '14 at 19:15
  • 1
    This is probably one of the top 10 most asked JavaScript questions. – Felix Kling Mar 02 '14 at 19:16
  • More duplicates: http://stackoverflow.com/q/1359018/218196, http://stackoverflow.com/q/11294997/218196, http://stackoverflow.com/q/16462052/218196 – Felix Kling Mar 02 '14 at 19:17

2 Answers2

35

You need to use .on to handle events of dynamic elements.
try this:

  $(document).on('click', 'p', function(){
     $(this).hide();
  });

DEMO

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
6
$(document).ready(function(){

 $("#add").click(function(){
     $("#containerDiv").append("<p> I should hide as well if you click me </p>");
  });

 $("body").on("click","p", function(){
     $(this).hide();
  });

});
Subash Selvaraj
  • 3,385
  • 1
  • 14
  • 17