JavaScript Allocation
JavaScript allows to place JavaScript code anywhere in an HTML document and you can also put multiple number of scripts in a document.
There are 3 most preferred places to include JavaScript code. They are:
- Within <head> tag
- Within <body> tag
- Using external JavaScript files
JavaScript Within <head> tag
Here is an example of JavaScript within <head> tag:
Example:
<html>
<head>
<script type="text/javascript">
function jsexample() {
alert("Hello this is js within head tag!")
}
</script>
</head>
<body>
<h1>JavaScript within head tag </h1>
<input type="button" onclick="jsexample()" value="Click Me!">
</body>
</html>
<head>
<script type="text/javascript">
function jsexample() {
alert("Hello this is js within head tag!")
}
</script>
</head>
<body>
<h1>JavaScript within head tag </h1>
<input type="button" onclick="jsexample()" value="Click Me!">
</body>
</html>
Run Example
JavaScript Within <body> tag
Here is an example of JavaScript within <body> tag:
Example:
<html>
<head>
</head>
<body>
<h1>JavaScript within body tag </h1>
<input type="button" onclick="jsexample()" value="Click Me!">
<script type="text/javascript">
function jsexample() {
alert("Hello this is js within body tag!")
}
</script>
</body>
</html>
<head>
</head>
<body>
<h1>JavaScript within body tag </h1>
<input type="button" onclick="jsexample()" value="Click Me!">
<script type="text/javascript">
function jsexample() {
alert("Hello this is js within body tag!")
}
</script>
</body>
</html>
Run Example
Using External JavaScript
to use external javascript you have to create an javascript file with .js extension and link this file to the HTML document. Here is an example using external JavaScript file named myJs.js:
In myJs.js:
function jsexample() {
alert("Hello this is js in external file!")
}
alert("Hello this is js in external file!")
}