I am trying to add behaviour to DOM objects inserted via AJAX.
From what I read in the jQuery Api Docs I think it would be best to have some scoped onInit(scope) handler to perform event binding on the new content.
So far I've got this:
function onInit(scope) {
console.log('init', scope);
$('.sometestclass', scope).css({'color':'red'});
}
(function($) {
$(document).ready(function(){
$(document).on('click', '.ajax-button', function(event){
event.preventDefault();
$target = $(this);
$.ajax({
url: 'validUrl',
...
success: function(data) {
var $new = $target.replaceWith(data);
onInit($new);
},
});
});
onInit(this);
});
})(jQuery);
Via firebug I can verify the ajax call is succesfull, the contents gets replaced as desired. onInit gets called in the document.ready event and after the ajax.sucess event. There are no errors shown in the firebug console.
Yet there is no reaction to the second onInit($scope) call.
What am I doing wrong here?
The jquery version used is 1.9.1.