To add javascript in html page we have 3 ways. Adding javascript inline, adding javascript in head section adding javascript via js file.
Where can we write javascript in html page?
Actually we can declare or write javascript anywhere in our html file but not before <head> start and not after </body> body end, and not between </head> <body> head end and body start. While we can declare javascript anywhere but we have to care if our javascript is outputting something which use CSS from a CSS file then we should declare javascript before that file declaration. Cause browsers like IE do not pick such things. So keeping things in sequence is necessary.
Write direct JavaScript in html page
Let’s say we are writing a javaScript code which alerts a box saying hello world, We can add that javaScript like following.
[code lang=”js”]
<script type="text/javascript">
alert("Hello World!");
</script>
[/code]
Above code will return a alert box saying hello world. You can write javaScript like this anywhere in your page but not before <head> head start not between head end </head> and body start <body> and not after </body> body end.
Inline JavaScript calling javaScript via html tags
Let’s say you have an image in your html page and you want when you click on image an alert box come up and ask do you really want to see me? There are several ways to do this but let’s add inline javaScript to see what happens. But we have to call javaScript by any event like we can call javaScript via onclick=””, onmouseover, onfocus, onblur and many more. We will call that alert box onclick like following.
[code lang=”html”]
<img src="myimage.jpg" onclick="alert(‘Do you really want to see me?’);" />
[/code]
Adding JavaScript in separate file.
First of all you have to create a javaScript file simply go to a text edito create a new file and save it as myj.js remember .js extension is necessary. So double check if you have not created a file like myj.js.text that would be a text file not js file. Now lets write an alert box in this file.
[code lang=”js”]
alert("I am working from JS file!");
[/code]
Now we have created our javaScript file and have written a one line javaScript code in it, remember inside javaScript file we do not start javaSCript with <script type/text/javaScript>. Well let’s include a javaScript file into our html file and see if that works.
Go to your html file and select where you want to put that file, that can be after <head> head start not between head end and body start and not after body end but inside body too. We are adding our javaScript file inside head section.
[code lang=”html”]
<html>
<head>
<title>Adding JavaScript</title>
<script type="text/css" src="myj.js"></script>
</head>
[/code]
once you run above code from your html file you will see an alert box which we declared in myj.js file. that’s all to add javaScript in html file.