what is the rule around calling functions from one js to another ? I thought that this worked but i am not running into issue (figured it out through firefox) that a function in another js file doesn't seem to be recognized in my first js file.
Is there some rule around ordering or some trick you have to do to get this to work?
It has to be accessible in the global scope somewhere. For example:
// file1.js
function hello() {
alert("Hello, world!");
}
// file2.js
$(function() {
hello();
});
Likely, you have something like this:
// file1.js
$(function() {
function hello() {
alert("Hello, world!");
}
// ...
});
// file2.js
$(function() {
hello();
});
hello
is only in scope of the closure defined in file1.js
. Therefore, to access it in file2.js
, you'd have to export it to somewhere where file2.js
can get at it:
// file1.js
$(function() {
function hello() {
alert("Hello, world!");
}
window.hello=hello;
});
// file2.js
$(function() {
hello();
});
Also, the script where the function is defined must be loaded, parsed, and executed before the function can be called from another script.
Are you calling the function in an event handler, or immediately when the javascript file is loaded? If it's not in an event handler, then load order is important. If you have circular dependencies, you may need to delay some of the initialization with a "DOM ready" or window.onLoad
listener.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With