Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a JavaScript function in another js file

People also ask

Can I call JS function from another file?

The import/export syntax is called JavaScript modules. In order to be able to import a function from a different file, it has to be exported using a named or default export.

How do I import a function from one JavaScript file to another?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.


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>

1st JS:

function fn(){
   alert("Hello! Uncle Namaste...Chalo Kaaam ki Baat p Aate h...");
}

2nd JS:

$.getscript("url or name of 1st Js File",function(){
fn();
});

You can make the function a global variable in first.js and have a look at closure and do not put it in document.ready put it outside

you can use ajax too

    $.ajax({
      url: "url to script",
      dataType: "script",
      success: success
    });

same way you can use jquery getScript

$.getScript( "ajax/test.js" )
  .done(function( script, textStatus ) {
    console.log( textStatus );
  })
  .fail(function( jqxhr, settings, exception ) {
    $( "div.log" ).text( "Triggered ajaxError handler." );
});

You could consider using the es6 import export syntax. In file 1;

export function f1() {...}

And then in file 2;

import { f1 } from "./file1.js";
f1();

Please note that this only works if you're using <script src="./file2.js" type="module">

You will not need two script tags if you do it this way. You simply need the main script, and you can import all your other stuff there.


use "var" while creating a function, then you can access that from another file. make sure both files are well connected to your project and can access each other.

file_1.js

var firstLetterUppercase = function(str) {
   str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
      return letter.toUpperCase();
   });
   return str;
}

accessing this function/variable from file_2.js file

firstLetterUppercase("gobinda");

output => Gobinda