I have a link that loads dynamic content into a div… there need to be a ton of additional ajax actions within that newly loaded dynamic content. Do I have to create a new delegate function for each of those actions in my success handler? (Does the delegate function, ideally belong in the success handler?) How can I consolidate these functions?
For example, I click the “view posts” button on the main screen. It loads in a bunch of posts into a modal window. Within that window, for example, there may be a ‘view comments’ button for each post, which makes its own ajax call and loads the comments directly into the modal window.
The two things I would like clarification on are what is the best practice for organizing these delegate functions. Secondly, when is delegate required/when is it not required?
Edit: Thanks guys. These were all great answers. I’m going to choose Ohgodwhy’s answer because he only has 245 rep.
There’s a great reference to the jQuery delegate function found in the jQuery documentation located at -> http://api.jquery.com/delegate/
Delegate monitors a “parent” and applies a function that allows for a callback on all child elements, regardless if they’re dynamic or not.
What’s important to note is that the delegate feature has since been replaced by the .on function in jQuery 1.7. You can monitor all DOM changes with the .on feature, which is also a replacement of the .live function.
The proper syntax to monitor and ensure that functions are bound to all elements added on/after DOM load is ->
EDIT
If you wanted to target all tag s with a class of “george” and ensure that the functions are run on all that are currently and will be in the future loaded, then you would do
This should make sense.