I am working on a page where elements are loaded via AJAX, it is a CMS type software and I have no access to the ajax, nor do I know it's callbacks.
I want to run my function when a specific part of the page is loaded, how can I do this when AJAX is involved?
My JavaScript, which works fine by itself: Fiddle:
var personalitet = document.getElementById("personalitet").innerHTML;
document.getElementsByName("form[5553]")[0].value = personalitet;
I have tried:
document.getElementById("personalitet").onload = function() {
document.addEventListener("DOMContentLoaded", function(event) {
window.onload = function(){
None of which work, as the elements are not loaded at the time my script looks for them.
You could use a mutation observer.
var observer = new MutationObserver(function(mutations) {
for (var i = 0; i < mutations.length; i++) {
// PUT ACTIONS HERE
console.log(mutations[i].type);
}
});
var observeElements = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(document.body, observeElements);
This will let you know when anything in the body has changed. Read more about the MutationObserver if you wanna get fancy.
It's not quick, though, and you should investigate if you could abuse your CMS to not get in your way. And it needs to call the last line before any mutations occur or it won't work.