m0j1 m0j1 - 1 month ago 12
HTML Question

Calling a javascript function in another js file

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.
Thanks


Edit:

Here's sample codes:

second.js


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


first.js


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

Answer

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>

It works fine :)

Comments