Embedding JavaScript
Saturday, January 10th, 2009There are several ways to embed JavaScript into your HTML pages . Lets look at them
the <SCRIPT> tag .
JavaScript code appears between a <SCRIPT> and a </SCRIPT> tags . You can use just the basic <SCRIPT> tags for your scripts like the following
<SCRIPT>
document.write(”A JavaScript example “);
</SCRIPT>
which gives us the following output
document.write(”A JavaScript example “);
there are a number of attributes which we can use with the <SCRIPT> tag
LANGUAGE
This is used to specify what scripting language the script is written in . In the majority of browsers the default attribute is JavaScript . But you have to be aware that there is also VBScript as well . If you were to mix VBScript and JavaScript and didn’t specify the language you would get some interesting problems cropping up . You can set the LANGUAGE attribute to the actual version number of JavaScript so if you set it to JavaScript 1.1 you would get all of the features of JavaScript 1.1 but if your script had features that were introduced in a later version of JavaScript the script would fail .
SRC
this is used to specify the URL of an external script to be loaded and executed . These external files usually have a .js extension . So this would look like this <SCRIPT SRC = “sample.js”></script>
ARCHIVE
this is used to specify the URL of a JAR file that contains a script specified by the SRC attribute . JavaScript 1.2 required.
TYPE
This is only supported in Internet Explorer 4 and Netscape Navigator 4 upwards . The syntax is as follows
<SCRIPT TYPE = “text/JavaScript”>my javascript </SCRIPT>
Event Handlers
JavaScript code can also be put into the handler attributes of HTML tags . These attributes always begin with on and some examples are onClick , onBlur and onMouseDown . The code is executed when the event occurs so for example if you press a button and have JavaScript code attached to the button this will execute when the button is pressed . Here is an example .
Here is the HTML for this example
<INPUT TYPE = button VALUE = “Press me for an alert box”
onClick=”alert(’damn annoying alert box example’);”>
JavaScript URLs
A JavaScript URL is a special type of URL . A JavaScript URL does not send or retrieve any information like a normal URL except as a side effect A JavaSCript URL is used to execute a script . JavaScript URLs occupy a single line , so if the contain more than one statements , semi-colons should be used .
Here is an example
alert box example here is the HTML code for this stunning example
<a href=”javascript:alert(’another annoying alert box’)”>alert box example</a>
