I am using Jquery to dynamically add some HTML into a page.
Now this new HTML code should trigger additional Jquery functions to enable more processing to be done but this new HTML code isnt recognized and thus the additional Jquery functions arent triggered.
How can I get the new HTMl code to be recognized and the additional functions triggered?
Thanx
There are 2 concerns normally, event handlers and plugins, which are two different things.
Part 1: Event Handlers
Event handlers are easy, because they act upon events, events behave identically no matter when the element as added. For this there’s
.live()and.delegate(),.live()listens for events ondocumentand runs if an event comes from an element that matches the selector, let’s take a table row for example:This would find all current table rows, when it ran and bind a
clickevent handler to them, the same as.bind('click', function). Then there’s.live(), like this:This listens for the
clickevent to bubble up todocument(this happens automatically, by default) and executes the handler…current and future elements behave the same way here. This means it works for both. Then there’s.delegate()which is a local version of.live()like this:If you’re just adding rows to
#myTablebut not removing/adding the table itself, the same type of listener for bubbling events can sit there, instead of all the way up ondocument, this means the event has to bubble fewer times before reaching the handler you want to execute.Part 2: Plugins
Plugins are a bit trickier, because they take elements and do things with them (this is true for most plugins). You have two decent options here, either running the plugin when new elements yourself, for example loading via
$.ajax()or a shorthand version would look like this:This finds new
<tr>elements, but only in a local context (in the returned HTML) and executes only on those elements. Alternatively, there’s a plugin for this, less efficient, but usually not a noticeable difference on most pages. The.livequery()plugin actively looks for and acts up new elements, the same code would look like this:Either of these are valid solutions, just see which fits your needs better.