we can write JavaScript language code anywhere in an HTML page, But most preferred place where we can write JavaScript code are follows:
write JavaScript within <head> tags
write JavaScript within <body> tags
write JavaScript within <body> and <head> tags
we can also write JavaScript code at external file and then include in <head> tags.
write JavaScript within <head>…</head> tags
If we want to run JavaScript function like alert, confirm box on some event like button click, then we can place JavaScript in the <head> tags as follows:
<html>
<head>
<script type=”text/javascript”>
function Hi()
{
alert(“Hello Meera Academy”);
}
</script>
</head>
<body>
<input type=”button” onclick=”Hi()” value=”Good Morning” />
</body>
</html>
The result of JavaScript code in <head> tags are:
write JavaScript within <body>…</body> tags
If we want to diaplay or write some text on HTML document while page loads, then write JavaScript code in the <body> tags of the HTML page.
<html>
<head>
</head>
<body>
<script type=”text/javascript”>document.write(“Hello Meera Academy”)
</script>
</body>
</html>
The result is :
write JavaScript within <head>…</head> and <body>…</body> tags
<html>
<head>
<script type=”text/javascript”>function Hi()
{
alert(“Hello Meera Academy”)
}</script>
</head>
<body>
<script type=”text/javascript”>document.write(“Hello Meera Academy”)
</script>
<br/>
<input type=”button” onclick=”Hi()” value=”Good Morning” />
</body>
</html>
Result are :
Write JavaScript in External File :
For write JavaScript in external file, we need to create JavaScript code file with an extension of .js.
The .js file is not a HTML document, write below code in JavaScript file
function Hi() {
alert(“Hello Meera Academy”);
Now call this file in our HTML document we need to write some syntax in <head> section.
<html>
<head>
<script type=”text/javascript” src=”javascriptfile.js” ></script>
</head>
<body></body>
</html>
I hope this JavaScript tutorial will help you…..