JavaScript works with HTML to bring interactivity to otherwise static documents and can be embedded inside HTML documents in three ways:
- The code is placed between <SCRIPT> - </SCRIPT> tags.
- Code is included inside an HTML tag.
- The entire code is placed in another file, which is called through the SRC attribute of the <SCRIPT> tag.
Using the <SCRIPT> tags
JavaScript code is most commonly included between <SCRIPT> - </SCRIPT> tags. For example:
<HTML>
<HEAD>
<TITLE>Page title</TITLE>
</HEAD> <BODY>
<SCRIPT LANGUAGE=”JAVASCRIPT” TYPE=”TEXT/JAVASCRIPT”>
<!–
some javascript code
//–>
</SCRIPT>
</BODY>
</HTML>
The LANGUAGE attribute explicitly informs the browser that the enclosed code is JavaScript. The TYPE specifies that the code is in TEXT format.
The <!– and //–> are placed around the code and hide it from browsers that do not understand JavaScript. I advise you to always use these “code hiding” tags since their inclusion is harmless; however if you leave them, the document display is completely ruined in non-JavaScript browsers.
JavaScript code inside HTML tags
To make interactive pages you need to catch or recognise user actions (also called events). The events generated by the user may be mouse clicks, mouse movement etc. To capture these events, we employ small JavaScript code that is placed right inside an HTML tag. Such code is called an event handler.
<a href=”http://www.computereducationworld.com” mce_href=”http://www.computereducationworld.com” onmouseover=”alert(’Go back to Home Page’)”>Home Page</a>
Here we have an anchor tag that surrounds some text (’Home page’). onmouseover is an event handler and as its name suggests,
it manages a mouse over action. In this case, onmouseover event handler triggers some response whenever the user moves the mouse cursor over the text enclosed between the anchor tags.
Placing JavaScript code in another file
Another common practice is to place the entire JavaScript code in another file. This external file can then be called using the SRC attribute of <SCRIPT> tag.
<SCRIPT LANGUAGE=”JAVASCRIPT” src=”mycode.js” mce_src=”mycode.js” TYPE=”TEXT/JAVASCRIPT”>
<!–
//–>
</SCRIPT>
Note that the external file containing the JavaScript code has .js extension. It is included in the HTML document through the SRC attribute that takes the URL of the file as its value.
There are three main advantages in using this technique. Firstly, you don’t need to place the code in all HTML documents, secondly, if a change is required you have to modify only one file instead of several and thirdly, it protects (though partly!) precious code. However, the main disadvantage is that the has to locate and open one more file.
