makaroN makaroN - 9 months ago 32
HTML Question

Access to ElementById from different javascript file

In javascript file

inClockingModels.js
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
id="tipkovnicaModalSlika"
in other javascript file
inClocking.js
. I tried with this one but its not working:

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


How can I access to
getElementById()
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: http://api.jquery.com/on/