home -- outline -- lectures -- assignments -- discussion -- tips -- links --



Monday March 10

The wonders of Javascript




Ok, first of all, for anything and everything JavaScript, see: Netscape's JavaScript Guide.

This entire lecture comes from the material contained in these pages (less the propaganda).

What is Javascript?

According to our friends at Netscape:
  • cross-platform, object-based scripting language for client and server applications
  • lets you create applications that run over the Internet.
  • supports client applications and server applications
  • can create dynamic HTML pages that process user input and maintain persistent data using special objects, files, and relational databases (sound familiar??)

JavaScript Basics

Despite the differences between client and server side JavaScript, there are some basic similarities which Netscape calls "the Core Language" (sounds so important!)

  • Keywords, statement syntax, and grammar
  • Rules for expressions, variables, and literals
  • Underlying object model (although client-side and server-side JavaScript have different sets of predefined objects)
  • Predefined objects and functions (we'll get to these later)

Some important things to note:

  • Different versions of JavaScript work with specific versions of Navigator.

    (JavaScript 1.2 is for Navigator 4.0, some features available in JavaScript 1.2 are not available in JavaScript 1.1 and hence are not available in Navigator 3.0, etc

  • Unlike HTML, JavaScript is case sensitive

  • You may sometimes see a semicolon at the end of each line of JavaScript. In general, semicolons are optional and are required only if you want to put more than one statement on a single line.

  • JavaScript uses "methods", another name for operators or commands

  • JavaScript and Java are not the same thing!

    • Java is an object-oriented programming language designed for cross-platformability and type safety. It was designed with things like on-line banking, distributed programs and all other kinds of scary stuff in mind. Therefore, it has many built-in security features so that people will actually trust programs buildt with it (HA!).

    • These requirements make Java programming more complex than what Netscape calls "JavaScript authoring". JavaScript doesn't give you as much flexibility, but it is easy to use for certain, specialized things.

JavaScript on the Client Side

For now, let's concentrate on what Javascript can do for you on the Client side.

  • client-side JavaScript statements are embedded in an HTML page
  • can respond to user events such as mouse-clicks, form input, and page navigation

    For example, you can write a JavaScript function to verify that users enter valid information into a form requesting a telephone number or zip code. Without any network transmission, the HTML page with embedded JavaScript can check the entered data and alert the user with a dialog box if the input is invalid.

  • another example: cool highlights on buttons, playing sounds after an event

Using JavaScript on your HTML pages

  • You can embed JavaScript in an HTML document in the following ways:
    • As statements and functions within a < SCRIPT > tag.
    • By specifying a file as the JavaScript source (rather than embedding the JavaScript in the HTML).
    • By specifying a JavaScript expression as the value of an HTML attribute.
    • As event handlers within certain other HTML tags (mostly form elements).

  • For now, we'll focus on using the <SCRIPT> tag.

The < SCRIPT > tag

  • JavaScript goes at the beginning of your html file, between tags, like this:



  • The <SCRIPT> tag signals that you are using JavaScript and which version as well.
  • The <!-- COMMENT helps hide this code from old browsers who don't use JavaScript.
  • Then there is some code, in this case, writing to the current page.
  • The // END COMMENT --> ends the hiding so we can continue with the html
  • Finally, the </SCRIPT> tag ends the script.

  • See this code in action, here

  • See your first error message, here

    Can you find the error?

Functions in JavaScript

We have been using Perl to write cgi, but we have never actually introduced the idea of a function. A function is a block of code that performs some operation. This block always has a name, so that it can be "called" (used) and often has arguments, so that it knows what to act upon when called. Why use functions? Because if you store some code in a function, you can just call it instead of writing it out all the time.

Consider your Rolodex assignment, as well as the Virtual Museum. There were several times that you searched several files for a particular keyword. While the conditions of this search changed, the basic operation was ususally the same. When it seems like you are writing the same code over and over, it's time to start thinking about functions.

So here is an example of a function (located in the HEAD of a html document) and a subsequent "call" in the BODY of the same document:

            <HEAD>
            <SCRIPT LANGUAGE="JavaScript">
            <!-- Hide script from old browsers
            function square(number) {
               return number * number;
            }
            // End script hiding from old browsers -->
            </SCRIPT>
            </HEAD>

            <BODY>
            <SCRIPT>
               document.write("The function returned ", square(5), ".");
            </SCRIPT>
            <P> All done.
            </BODY>


So how does this work??

The function square takes one argument, called number. The function consists of one
statement 

         return number * number

that indicates to return the argument of the function multiplied by itself. The return
statement specifies the value returned by the function. In the BODY of the document, the
statement

         square(5)

calls the function with an argument of five. The function executes its statements and
returns the value twenty-five. The script displays the following results:

          The function returned 25.
          All done. 

The square function used the line

        document.write(...)

to display output in Navigator, like this

NOTE: Another thing we mentioned before were objects...for now, just think of objects as extra special functions.


Dynamic Generation of HTML

As we just saw, the write method of document displays output in the Navigator. Just like the print statement in Perl, the write method lets you display text conditionally or based on variable arguments.

The write method takes any number of string arguments that can be string literals ("this is a literal string") or variables (like $var in Perl). Now, in Perl, we just separated variables with spaces in our print statements: print "$last $first"; In JavaScript you use the string concatenation operator (+) to create one string from several.

Consider the following script, which generates dynamic HTML with Navigator JavaScript:

            <HEAD>
            <SCRIPT>
            <!--- Hide script from old browsers
            // This function displays a horizontal bar of specified width
            function bar(widthPct) {
               document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>");
            }

            // This function displays a heading of specified level and some text
            function output(headLevel, headText, text) {
               document.write("<H", headLevel, ">", headText, "</H",
                  headLevel, "><P>", text)
            }
            // end script hiding from old browsers -->
            </SCRIPT>
            </HEAD>

            <BODY>
            <SCRIPT>
            <!--- hide script from old browsers
            bar(25) 
            output(2, "JavaScript Rules!", "Using JavaScript is easy...")
            // end script hiding from old browsers -->
            </SCRIPT>
            <P> This is some standard HTML, unlike the above that is generated.
            </BODY>


How this works:

The HEAD of this document defines two functions:
  • bar, which displays : an HTML horizontal rule of a width specified by the function's argument.
  • output, which displays : an HTML heading of the level specified by the first argument some heading text specified by the second argument and some paragraph text specified by the third argument.
The document BODY then calls the two functions to produce the display shown here