Teach Yourself Web Publishing with HTML 4 in 21 Days

Chapter 19: Creating Javascript Scripts

 

 

Objectives:

This chapter discusses a method for putting a program script inside the HTML page so that it runs on the browser, instead of on the server. Objectives important to this chapter are:

  • defining Javascript
  • understanding reasons to use Javascript
  • understanding the use of the <SCRIPT> tag
  • introduction to Javascriptcommands and syntax
  • creating a Javascriptprogram
Concepts:
Javascript is a script language for writing computer programs that run in an HTML document. The significance of it being a script language is that we can write it directly in the HTML page itself, and we do not have to compile it as a separate program. Javascript was created by the Netscape company, and it was originally called LiveScript.

Javascript is meant to be easy to use, easy to write and modify, and easy to copy from one page to another. It is somewhat related to the Java language, which was created by the Sun company. Java, however, is a compiled language and requires a Java compiler to create the program. Java also requires that a Java support module (called a Java Virtual Machine) be installed on any computer before a Java program can be run on it. Javascript only requires that you use a browser that understands Javascript Java is not Javascript, and Javascript is not Java. (Read this paragraph again until you understand the difference.)

Javascript is an alternative, in many cases, to Common Gateway Interface (CGI) programs. CGI programs run on a server. Javascript can replace a CGI program when you cannot or do not have permissions to run one on a web server. The Javascript program is written in the HTML document, sent to the browser, and it runs there, removing the need to send a message to the server (asking it to run a program) and the need to wait for a response.

To create a Javascript program, you must use the <script> tag. This is a paired tag, and the pair enclose the program you will write. The opening tag requires an attribute naming the language your script is written in, so the format will be like this:

  <script language="Javascript">
Laura recommends that we place the <script> tag inside the HEAD section of the page. You will notice that this practice is not often followed by HTML writers. This is fine. The language is a bit forgiving.

Two rules about comments are necessary. Since not all browsers understand Javascript, we enclose the program lines within HTML comment markers, as on page 598.

<html>
<head>
<title>test script</title>
<script language="Javascript">
<!-- a remark is placed here, enclosing the script commands
// a remark in the script is created with double slashes
// this is another remark in the script
-->
</script>
</head>
<body>
the actual page goes here
</body>
</html>
	

The <script> and </script> tags themselves are not inside comments because the browser will simply disregard any tags it does not understand. The program lines are another story, so we protect other browsers from the program by disguising the program as a comment. A browser that understands Javascript, on the other hand, will understand the <script> tag and switch rules until it sees the closing </script> tag. Switch rules? Yes, actually. Once a recognized Javascript begins, the browser will expect that comments will be marked by C++ style comment markers: double slashes at the beginning of each comment line. A C++ comment is anything that follows a double slash. C, C++, and C# are programming languages that are similar to Javascript (Note that a C++ comment marker is not the same as a C comment marker. Only the double slash is recognized as a comment marker by Javascript)

For those who wish to hide their scripts from the user, the <script> tag can use the src attribute, to specify a file that contains the script to be run. This is efficient in the sense that if you need to make a change in a program that several HTML pages use, you need only change the external file they reference, instead of changing all the pages individually.

Javascript is an object oriented language. In general, an object can be anything that is stored in memory. In relation to programming, an object is often a piece of a larger thing, and each piece has properties (or attributes) that can be given values. For instance, all the parts of an HTML page being displayed can be thought of as objects inside a window object. The document object in that window has properties (attributes) such as the background color. This object and property are referred to by the phrase

   document.bgcolor 
which follows the general syntax of
   object.property

Different kinds of objects have different kinds of properties. Objects also have methods. A method is like a built-in program (or function) that the object knows how to run. Methods are used with the same kind of syntax as properties, except that the name of the method is usually followed by a set of parentheses. For example, if we have a form on the screen, and we wish to submit the form, the code to do so might be

   form.submit()
Other properties and methods are discussed on pages 600 - 601.

Another important concept in object oriented program languages is the event. An event is when something specific happens in the program or from interaction with the user. Several events are listed on page 603.

An event is defined to happen whenever a specific action takes place, and the fact that it happens is noticed by an event handler. An event such as the user placing the cursor in a field is noticed by the handler onFocus, while clicking a button is handled by onClick. The events are associated with specific objects. That is, each button would have its own Click event and onClick handler.

What happens when an event takes place is the next concept. Events are often associated with functions. A function is a sub-program that is already included with your object or that you can write as an add-on for it. Functions are used to make programs more modular, so you can use pieces of one program in another one. They also help when writing a program, in that you can concentrate on small tasks, one at a time, and write a function for each task, instead of worrying about the program as a whole.

You can write a function in Javascript with code like this:

<script language="Javascript">
function functionName (arguments) {
  program instructions go here
}
</SCRIPT>
The curly braces are block markers, showing where the body of the function begins and ends. The function is preceded with the word "function" to let help the browser find it. Functions must have names, to tell them apart, and to give you something to call them. You call a function when you tell it to run.

In order to call a function, you have to use the event handler as an attribute to a tag, an equal sign, and the name of the function you are calling. For example, we could put an onClick handler in a button tag, and have the handler call a function to check something in the form, as Laura's example;

<input type="SUBMIT" onClick="processclick()">

You can use variables in Javascript programs, much as you do in other languages. To use a variable, first declare that it exists with code like:

var variablename = some_value;
Note that this program line ends with a semicolon, just as program lines do in C or C++. The line not only declares the variable named, it also gives it an initial value, or initializes it. A variable may be declared and given a value in any of the ways depicted on page 604. There we see a string as the value, a number, the value of a property, and the return value of functions used as the value being assigned.

On page 605, we see a list of math operators used in Javascript Most of these are the standard symbols for addition, subtraction, and such. More C-like operators are the incrementation and decrementation operators, ++ and --. They simply add one or subtract one from the current value of a variable. As used in C, we are also allowed to use the operators on page 606, which are clearly explained there. If you would like more explanation, see my notes for CS215, particularly the chapter on C Operators.

The next topic is creating the Javascript program itself. Laura explains that the syntax of Javascript is similar to C and to BASIC. The code is executed a line at a time, top to bottom. Her example on the bottom of page 606 would simply write two lines on the document itself. Note that in the example, she has not inserted the HTML remarks. In a real script you would do so.

Of course, in real program, you don't just write lines to a page. If you did, you wouldn't need the program to do it. So, Javascript allows for branching and looping. Branching is deciding which of a set of alternatives to take. The if statement is used to decide whether to execute a block of code. The word if is followed by a set of parentheses which contain a test. If the test is true, the block of code following the test is executed, if not it isn't.

A test condition is usually constructed with a relational operator, such as those in the chart on the bottom of page 607. These are the standard relational operators in C.

An if statement can also be modified to include an else clause. This is useful for situations that have only two possible outcomes.

Looping is repeating the same lines of code some number of times. Javascript has two kinds of loops to use:

  • the for loop is often used when the programmer knows how many times to repeat a block of code
  • the while loop is often used when the loop needs to repeat until something changes.

It is best to remember to test the logic of a loop before turning it loose on the public. A badly worded test can result in an infinite loop, which runs forever unless terminated by the user. This will not make your web pages popular.

Since this chapter does not actually give you any good examples of Javascripts, or reasons for using them, I assign you to search the Internet for references and examples.