I have a page in which content is brought in via ajax. The problem I am having is adding the relevant event listeners after the content has loaded. Is there a way to tell the browser to run all the scripts from the head again?
Below is a simple example of code that gets run from the head of the page, obviously any new html elements matching .RRCustomizeBox .customize brought in via AJAX will not have the following click event.
e.g.:
_vvdCMS.kklsRegions = {
init: function (){
$(document).ready(function(){
$('.RRCustomizeBox .customize').click( function(){
_vvdCMS.kklsRegions.showRRCustoms(this);
});
});
},
showRRCustoms: function(obj) {
var objParent = $(obj).parent();
objParent.find('.RRCustomizeBoxForm').fadeIn(700);
}
}
_vvdCMS.kklsRegions.init();
You can put all your initialization code in a function and call that function from two places:
For example:
You will have to make sure that any content that is not replaced does not get multiple event handlers installed.
Or, second option, you for some types of logic (like mouse and key events), you can use delegated event handling and install the event handling once attached to a static parent object that is not replaced and the event handling will work without change for your dynamic content that changes underneath.
For that, you use the delegated form of
.on():