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();
});
});
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.
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
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 .
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.
You need to use .on
to handle events of dynamic elements.
try this:
$(document).on('click', 'p', function(){
$(this).hide();
});
DEMO
$(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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With