m0j1 m0j1 - 1 year ago 100
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.


Here's sample codes:


document.getElementById("btn").onclick = function(){


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

Answer Source

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 (){

2.js :


index.html :

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

It works fine :)

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