0

I have 2 external js files and I need a function to be called in html when document.body.innerHTML adds an element. There is a function in the other file that I want to get called when this div is added. How would I call the function when the element is created?

//pseudo code
//first file:
document.body.innerHTML += "<div></div>"
//second file:
var foo = function() {
alert("foo");
}
//when div is added call foo.
  • Can you not just call `foo()` after than statement? Btw, using `innerHTML +=` is [bad practice](http://stackoverflow.com/q/595808/5743988) and causes the DOM to be reloaded. – 4castle Nov 04 '16 at 04:55
  • I know it is frowned upon but it is much easier to write than [this](http://stackoverflow.com/a/718106/7027404) – IlllIIllllIlllIllllllIlllllIIl Nov 04 '16 at 05:02

2 Answers2

1

If the code executes sequentially, when you add the div the function foo hasn't been defined yet because it's in the second file. You would need to load your files in reverse order, i.e load the second file first and the first file second, so that when the div is added the foo function is defined. Then you can call it like any other function.

document.body.innerHTML += "<div></div>";
foo();

If you can't change the order the files are loaded, you could execute the code in the first file after foo() is defined by putting it in a timeout:

setTimeout(function(){
    document.body.innerHTML += "<div></div>";
    foo();
}, 0);
Ryan Jenkin
  • 864
  • 8
  • 11
0

I think you need to use jquery to keep watch on body to identify it :

$(document).on('DOMNodeInserted', function(e) {
    if (e.target.tagName == 'body') {
       console.log('something inserted')
       foo();
    }
});

function foo () {
 alert("foo");
}
Jigar7521
  • 1,549
  • 14
  • 27