writing javascript code in a separate file

If  the javascript functions are defined in the same file where they are used, it will increase the code of file and many javascript functions will not be reusable in other files. So it is recommended to put the javascript code in a separate file and call that file in html document (just like we did in case of style sheets)

The following code defines a javascript file in which a function is defined. The file is called in other html file.

jscripts.js

function myfunction()
{
var response = confirm("Are you sure?");

if( response == true )
{
document.write("Response is positive");
}
else
{
document.write("response is negative");
}

}

The file is called in the following html file

index.html

<html>
<head>
<title>index page</title>
<script src="jscripts.js" type="text/javascript"></script>
</head>
<body>
<input id="btn" name="btn" type="button" value="click here" onclick="myfunction();" />
</body>
</html>

Add a Comment

Your email address will not be published. Required fields are marked *