I faced the same problem recently. Most of plugins need to be applied to elements by calling them in $(document).ready()
, I wanted to call the same function not only for content which was there just after the document was loaded, but also for those elements which arrived by Ajax call later.
After googling a while I found two types of recommendations:
1. To bind to final event of every ajax call.
2. To bind to some element specific event, (like focus()
) to run your code.
In the first case you need to take care about it in your ever ajax call.
The second did not worked for all cases well.
So my solution is to call the same function from $(document).ready()
and $(document).ajaxSuccess()
. In this case I need to prevent one and the same manipulation to happen to the same control twice. SO I used a special class I am applying to all visited elements.
function doOnReady() {
$(":input[data-autocomplete]").each(function () {
//Check wether allready visited
if (!$(this).hasClass('visited-by-on-ready')) {
//Do your staff
$(this).autocomplete({
source: $(this).attr("data-autocomplete"),
});
//mark as visited
$(this).addClass('visited-by-on-ready');
}
});
}
$(document).ready(doOnReady);
$(document).ajaxComplete(doOnReady);