I am using a jQuery to populate data from CSV file.
I need to give an event to the elements which created dynamically.
Now the event is not getting on the dynamically created data.
Use .on
to bind events to dynamically added elements.
You can use the jQuery .on()
functionality for that.
$(document).on('click', 'div.my_new_dom', function() {
// do magical things
});
This will bind new DOM to the jquery automgaically when it's added to the document.
Check out this link for detailed description. http://api.jquery.com/on/
You can do this one of two ways:
You can add the event to each element as it is being created (preferred).
OR
You can bind the event to a parent element or the document and filter it for the newly created element type or class, so that it applies to dynamically created elements as well (as @phpisuber01 has demonstrated).
The reason that I think the first option is preferred is that with the second option, you're binding a click event to the entire document. So every time you click (or do whatever your event is doing) anywhere on the page, checks must be done to see if the clicked element should fire the event. I'm not sure how big of a difference it is in performance, but it's something to consider.