Starting JavaScript

Embedding Script

Javascript statements are hidden in HTML comments to prevent incorrect interpretation by older browsers that do not recognize JAVA script. An example HTML document with embedded JAVA script is shown.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>An Example of JavaScript code</title>
<head>
<body>
<script language="JavaScript">
<!-- Use the HTML comment to hide JavaScript from old browsers
document.write("This text was written using JavaScript.")
// End hiding JavaScript -->
</script>
<NOSCRIPT>
You see this if your browser won't run JavaScript.
</NOSCRIPT>
</body>
</html>

Note that there are two tags used to implement this script example:

  • SCRIPT - The area between the <SCRIPT> and the </SCRIPT> tags defines the script program.
    • language - Defines the script language. Choices are JavaScript and VBScript.
    • SRC - Defines an external file containing the source code of the JavaScript. It may be a URL with the complete path to the script which may reside at another website. An example is:

      <script language="JavaScript" SRC="testscript.js">

  • NOSCRIPT - The area between the <NOSCRIPT> and the </NOSCRIPT> tag is run by browsers that can't run JAVA script or have the feature turned off.



Other Script embedding methods and information

  • Entities which begin with "&{" and end with "};" Example:
    <html>
    <head>
    <title>The entity method of using JavaScript.</title>
    <script language="JavaScript"><!--
    CGILink="http://www.ctdp.tripod.com/independent/web/cgi/index.html"
    // -->
    </script>
    </head>
    <body>
    <A HREF="&{CFILink};">Go to CGI Section.</A>
    </body>
    </html>
    
  • Comments are started with "//" for a single line, along with the "/*" to start a comment and "*/" to end a comment for multiple lines. The comments work the same as in C++.
  • In JAVA, a variable must be defined before it is used, therefore it is a common practice to place JavaScript definitions in the header section of an HTML file. The example below will randomly select and display a greeting in an HTML header of size three.
    <HTML>
    <HEAD>
    <TITLE>Common JavaScript definition practice</TITLE>
    <SCRIPT language="JavaScript">
    <!--
    Greeting = new Array(4); 
    Greeting[0] = "have a nice day."
    Greeting[1] = "it's a great day."
    Greeting[2] = "have a great day!"
    // -->
    </SCRIPT>
    </HEAD>
    <BODY>
    <CENTER><H1>This is a Greeting Example</H1></CENTER>
    <SCRIPT language="JavaScript">
    <!--
    i1 = Math.round(Math.random() * 3)
    document.write(("<H3>Hi, " + Greeting[i1] + "</H3>\n")
    // -->
    </SCRIPT>
    </BODY>
    </HTML>
    
  • Special characters include:
    • \b - backspace
    • \f - Form feed
    • \n - New line
    • \r - Carriage return
    • \t - Tab