Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery events do not work on dynamically appended elements

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();
  });

});
like image 956
user3371458 Avatar asked Mar 02 '14 19:03

user3371458


People also ask

Does jQuery work on dynamic content?

With jQuery, what happens is it bind event listeners on each DOM element inline and not on classes or ids. So when the binding method is called, events are bonded on the DOM loaded. To bind event on dynamically loaded DOM, we bind the event to the nearest static parent and give the element we want to bind event.

Is there a way to catch events to dynamically created elements using jQuery?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

How do you add an event handler to a dynamic button?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click .

How do I create a dynamic DOM element?

With document. createElement() method you can create a specified HTML element dynamically in JavaScript. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document.


2 Answers

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

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

DEMO

like image 108
Alessandro Minoccheri Avatar answered Oct 18 '22 20:10

Alessandro Minoccheri


$(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();
  });

});
like image 25
Subash Selvaraj Avatar answered Oct 18 '22 19:10

Subash Selvaraj