Calling js function in external js file from within a script tag

2.8k Views Asked by At

I have an HTML file with a script tag. In order to reuse the functions common to other pages, I have created an external JS file with some functions. Now, if I link the external JS file in the head and try to access the functions as attributes for HTML tag using onclick="functionname()", it works. But I want to call the functions in the external JS file within the script tag ( I need to pass parameters to the functions and I extract those values within the script tag), I am not able to do so. Is it even possible to call functions in the external file within the script tag? If yes, how can this be done?

2

There are 2 best solutions below

2
Gaurav Patil On
  1. Create js file. E.g. index.js
  2. Add index.js file in your HTML files using script tag
  3. Add onClick="functionName()" in your html

Make sure the function which you use must be present in the index.js file

Check Below Code

<body>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
    function call() {
        showAlert()
    }
</script>

<button onclick="call()">Call External Function</button>
</body>

First load external js file like below

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

Add new script tag and add one another function to call external function

<script type="text/javascript">
function callExternalFun() {
    showAlert()
}
</script>

After that add callExternalFun() in your HTML

<button onclick="callExternalFun()">Call External Function</button>

External JS code index.js which contains showAlert function

function showAlert() {
  alert("External JS Function")
}
0
Younes Meridji On

In the external js file:

function myExternalFunction(param) {
    //some code
}

In the html file:

<html>
   <head>
      <script type="text/javascript" src="<path to the external js file>"></script>
   </head>
   <body>
      <script type="text/javascript">
         //here you can call your external function
      </script>
   </body>
</html>