I have a div section that I'm dynamically populating via jQuery ajax:
$('#treeview').append(data.d);
Where data is a bunch of nested divs with different ids.
I also have some jQuery code that makes the divs into a treeview, with a +/- expand/collapse and dynamic data population:
$('div.tree div:has(div)').addClass('parent'); // Requires jQuery 1.2!
$('div.tree div').click(function() {
var o = $(this);
o.children('div').toggle();
o.filter('.parent').toggleClass('expanded');
BindGridView($(this).attr('id'));
return false;
});
The issue is when I paste the divs into the main treeview div all is well. When I dynamically create the exact same text, yes I've compared it, the expand/collapse & dynamic data population doesn't work; however I can see my correct div layout on my page.
I'm guessing that I need to add the click event & addClass when I'm doing the
$('#treeview').append(data.d);
But I can't figure out how.
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 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.
With document. createElement() method you can create a specified HTML element dynamically in JavaScript. Once created, you can insert (or add) the element to your web page, or add it to a pre-defined element or a dynamically created element. In fact, you can create an entire form dynamically using this method.
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event. Save this answer.
If you are dynamically adding elements to the DOM, then existing event handlers bound to a selector will not work (such as click
).
You need to use the live
function in order to have events from newly created DOM elements captured.
It should be noted (as it was in the comments by Zach L) that as of jQuery 1.7 live
has been deprecated in favor of on
. The general advice is the same (tracking dynamic elements), just the mechanism (on
vs live
) has changed.
live()
is deprecated.
From the docs:
Use .on()
to attach event handlers. Users of older versions of jQuery should use .delegate()
in preference to .live()
.
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