makaroN makaroN - 1 year ago 74
HTML Question

Access to ElementById from different javascript file

In javascript file

i have this function:

Modal.prototype.SetText = function(text, tipkovnicaModal) {
this.textElement.innerHTML = text + '<img id="tipkovnicaModalSlika" src = "' + tipkovnicaModal + '" alt ="Modalna tipkovnica" height="100" width="100" />';

I want to get img
in other javascript file
. I tried with this one but its not working:

document.getElementById('tipkovnicaModalSlika').addEventListener('click', ShowKeyboardMain);

How can I access to
from one javascript file to the other?

Answer Source

This should work as JavaScript running in a browser doesn't care what file other scripts are in, as they execute on a context, normally the window of the browser. What is important is the order in which they are evaluated.

You may need to wait for the window to have loaded before trying to add an event handler. Or you might have to wait until the dynamic element has been created.

If you are unsure when the dynamic element will become available, I suggest looking into event delegation, where you can add a handler to a parent element you know is ready to listen for events on its children via bubbling. If you are using jQuery this is extremely simple.

It is mentioned in the docs here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download