Anonymous Anonymous - 1 month ago 8
HTML Question

Is there a way to run a function in a separate file when a div is added? [No jQuery]

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.

Answer

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);