Reputation: 133024
When my document is ready, I want to run a javascript function on all elements with class "test".
$(document).ready(function
{
$('.test').doSomething();
});
Imagine that I also dynamically load some contents into a div with jquery/AJAX. That content may also contain elements with class test. How do I make sure that doSomething is called on them as well. In other words, I want a function to be called on all elements with class test as soon as they appear, regardless of whether they were there in the first place or loaded later dynamically. Of course, I could write
$('.test').doSomething();
inside the AJAX callback as well, but I'm hoping I could avoid writing the same code in every AJAX callback. Is this possible? Does this make sense?
Upvotes: 0
Views: 45
Reputation: 1443
An expansion of my comment above:
jQuery has a couple methods that let you register global handlers for all AJAX requests http://api.jquery.com/ajaxSuccess/ . You could use that and call doSomething
every time you make a successful request, filtering for .test
elements that have already had the method called.
There are a lot of ways you could accomplish the "filtering", but the absolute simplest way would be to add a class to every .test element after you fire the method.
$(document).ajaxSuccess(function () {
$('.test:not(.added)').addClass('added').doSomething();
});
This would simultaneously filter out ones you've already added.
Upvotes: 1