How to use external “.js” files

How to use external “.js” files

I have the following two javascript functions:


I would like to put them in external “.js” files


What is the correct syntax to call these functions?


Solution 1:

Code like this

          <script type="text/javascript" src="path/to/script.js"></script>
          <!--other script and also external css included over here-->
            <select name="users" onChange="showUser(this.value)">
               <option value="1">Tom</option>
               <option value="2">Bob</option>
               <option value="3">Joe</option>

I hope it will help you….

Solution 2:

Note :- Do not use script tag in external JavaScript file.


    <p id="cn"> Click on the button to change the light button</p>
    <button type="button" onclick="changefont()">Click</button>

     <script src="external.js"></script>

External Java Script file:-

        function changefont()

                var x = document.getElementById("cn");
       = "25px";           
       = "red"; 

Solution 3:

In your head element add

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

Solution 4:

This is the way to include an external javascript file to you HTML markup.

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

Where external-javascript.js is the external file to be included. Make sure the path and the file name are correct while you including it.

<a href="javascript:showCountry('countryCode')">countryCode</a>

The above mentioned method is correct for anchor tags and will work perfectly. But for other elements you should specify the event explicitly.

Related:  Why are parenthesis used to wrap a javascript function call? [duplicate]


<select name="users" onChange="showUser(this.value)">


Solution 5:

You can simply add your JavaScript in body segment like this:


<script src="myScript.js"> </script>

myScript will be the file name for your JavaScript. Just write the code and enjoy!

Solution 6:

I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.


Related:  Angular2 Observable - how to wait for all function calls in a loop to end before proceeding?