Calling a javascript function in another js file

m0j1 picture m0j1 · Sep 21, 2014 · Viewed 546.5k times · Source

I wanted to call a function defined in a first.js file in second.js file. both files are defined in an HTML file like:

<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>

I want to call fn1() defined in first.js in second.js. From my searches answers were if first.js is defined first it is possible but from my tests I haven't found any way to do that.

Here is my code:

second.js

document.getElementById("btn").onclick = function() {
    fn1();
}

first.js

function fn1() {
    alert("external fn clicked");
}

Answer

Fernando Mendez picture Fernando Mendez · Sep 21, 2014

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

You declare function fn1 in first.js, and then in second you can just have fn1();

1.js:

function fn1 () {
    alert();
}

2.js:

fn1();

index.html :

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>