Anonymous Anonymous - 1 year ago 59
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

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() {
//when div is added call foo.

Answer Source

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

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:

    document.body.innerHTML += "<div></div>";
}, 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download