JavaScript > Function

Code in external file in JavaScript

How to write the JavaScript code in external file and use it in the html page?

Create a new .js file called JavaScript.js (you can name it anything you like) and place following code inside.

function AlertMe()
alert("I am being called from external JavaScript file");

Note that JavaScript code is not wrapped with <script> tag if it is written in external .js file.

Now keep following script tag under <head> tag of the html page. Ideally the script blocks should be placed in the <head> tag however it’s not mandatory.

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

JavaScript code in external file

Now the AlertMe() method can be called from the html page on any event of the HTML page like onclick, onchange etc.

<input type="button" id="btnTest" onclick="AlertMe()" value="Click me!" />

JavaScript code in external file

 Views: 1360 | Post Order: 11

Write for us

Hosting Recommendations