JAVA FOR EVERYONE:
Javascripting Javascript
Copyright © 1996 Mona M. Everett. All rights reserved.
In a perfect world, one programming language would do for all of the flavors of computer platforms and
operating systems. Wouldn't it be nice if an application could run unmodified on four versions of Microsoft
Windows, two of the Macintosh, OS2, and a dozen incarnations of UNIX? Dream on—or maybe not! Think
for a moment about Web browsers in general and Netscape Navigator in particular. What do you have? It
runs on four versions of Microsoft Windows, two of the Macintosh, OS2, and a dozen incarnations of
UNIX. Because of the expanding importance of the World Wide Web, it was only a matter of time before
someone decided to give a Web browser a programming interface. The first attempt was Java, developed by
Sun Microsystems, and available for several platforms. Although Sun originally developed their own
browser, Hot Java, to run the language, a collaboration with Netscape facilitated development of a Java-
enabled Navigator. Java "applets" must be compiled by the developer. They can then be downloaded to the
machine on which a browser runs and "displayed/played," much like a GIF, by the virtual machine
(translation: interface between machine specific code and Java byte code) built into the browser. Java, unlike
C++ is truly object oriented. It has lost most of the deficits of C/C++ although, unfortunately, has kept the
terse and often cryptic syntax.
Javascript might be thought of as a "little brother/sister" of Java. It has the same syntax but only a subset of
Java's features. Unlike Java, Javascript is interpreted, rather than compiled. The code is part of the HTML
which resides in and determines the form of the Web page. In fact, you can have a page which is nothing
but Javascript and even have Javascript write the page. Javascript, like Java, is object oriented, and a
version of it exists for all of Netscape Navigator's platforms.
The Microsoft Windows world hosts three major "friendly" object-oriented and GUI-based languages and a
plethora of others less often seen. The major players are Visual Basic, Powerbuilder, and Delphi. All of
these, though, were much preceded by Apple's Hypercard which, to my way of thinking, is a considerably
more powerful language than any of the Windows latecomers as long as one is not interested in (1) inherent
color and (2) database access. Hypercard was originally developed for the original old black-and-white Mac
long before color monitors and ODBC became as common as weeds. Hypertalk (the scripting language of
Hypercard), though, has a feature which is not inherent to any of the aforementioned Window's languages.
Hypertalk can write Hypertalk. Not only can it write Hypertalk, it can even alter its own scripts. While
conservative programming aficionados might gasp at the concept (along with goto) smart-aleck assembly
language programmers know that that is one of the fastest ways to write code, and goto, in the guise of jmp,
is often the only game in town. But now that I have gotten in my dig at "proper" programming techniques,
lets talk about Javascript, which, by the way, sadly, has no hint of a goto statement.
Javascript is a language in its infancy. It has no hint of the nice drag and drop, click and code, interfaces
offered by Visual Basic and Delphi, although those niceties are on the way. Check out Adobe's PageMill
and Netscape's Navigator Gold betas, to mention two. It is also, at present, a very sparse language. You
have to work hard to produce sophisticated effects and in the process, find bugs of which neither Netscape
nor anyone else ever dreamed. Of course, some of these latter are claimed as "features." While C
programmers will be right at home with the language, if you have never written code before, or if BASIC or
Hypercard are more your style, Javascript, which embodies C's terseness, will look like someone's
mathematical nightmare. If you have never seen C code, suffice it to say that C/C++ are often described as
write-only languages. Reading them, even if you, yourself, wrote it last week, can be quite a chore. Further,
since Javascript is interpreted, it is also somewhat slow. So with all of these negative features, what is so
great about Javascript?
- First, it is free with Netscape 2.0+. And if you cannot afford to buy Netscape, the regularly appearing
betas are available free to everyone. If you use the betas, Netscape will be more than happy to hear from
you if you encounter bugs. They might even pay you for it.
- Second, Javascript is meant to be a language available to everyone. Well, if so, why make it look like C?
Javascript is a subset of Java which DOES look like C, but fortunately, has eliminated a lot of C's
shortcomings. Since Javascript IS so sparse, you will not have a plethora of statements and functions to
memorize. There are no obvious pointers, handles, and 1000+ API calls which comprise the heart of
Windows or Macintosh programming, to keep track of. If you do not know what any of those things are,
don't worry about it. Further, Javascript (and Java) cleans up after itself, unlike C, where you need to do it.
Best of all, if you can learn the Javascript syntax, neither C nor Java will look so cryptic any longer.
- Third, Javascript is a cross-platform language (relatively). Although there are some differences in
Netscape running on various platforms, these are slowly being weeded out. Each platform's Netscape
browser has its own native Javascript interpreter, but the Javascript which YOU write, just like HTML, will
be identical for any platform which supports a browser which supports Javascript. And speaking of
supporting Javascript, even Microsoft has declared that their browser will do it in future editions.
- Fourth, you do not need anything special to write it. Any old plain text editor, even Window's Notepad
or Mac's Teach Text will do. Just save your plain text file with an ".htm" or ".html" extension. Open up
Netscape, go to the File Menu and find "Open File..." Find the file you have just written and open it. The
Netscape browser will happily try to interpret any HTML and Javascript which you have written. Keep both
your simple text editor and Netscape open. Make changes in your text in the text editor and save them. Click
on Netscape to activate it, and then click on the Reload button. In rare cases, you may have to use Ctrl-R to
force a complete reload. Netscape will reread your code. Guess what! With what you already have on your
system, you have a complete and easy-to-use authoring system. If you really do not want to type in all of
the HTML tags, there are a lot of shareware products on the market which will type them in for you with a
button click.
- Last but not least, although Javascript cannot alter its own code, it is most definitely Hypercard-like in
that it can construct variable and objects names as well as HTML and JAVASCRIPT on the fly. It can
interpret the names as the objects which they represent, execute the Javascript which it has written, and
produce an HTML page. Consequently, although Javascript is, at the moment, lean, it is also extremely
powerful. Unfortunately, its most powerful aspects are the least likely to be exploited spontaneously unless
you are extremely creative or have had a lot of experience with a language like Hypercard.
The purpose of this column will be to teach you Javascript. However, there will soon be a number of books
out on Javascript, one of which I have contributed to; there are many good Web sites; and Netscape's
documentation, while it never keeps pace with the changes in the language, is well written and a good place
to start. You really do NOT need another place to read about how to construct simple Javascript; therefore,
this column will try to teach you some of those "powerful aspects" of the language. Besides, I never start at
the beginning...but just in case you DO, I will try to comment code well enough for you to follow it if you are
just starting out. I will also make the assumption that readers are already familiar with HTML. With that, let's
jump right in and write some Javascript. Script Tags Javascript is usually but not always written
between script tags, i.e.
<SCRIPT>
Your code here
</SCRIPT>
Although script tags can appear anywhere, they most often appear in the document header. They may also
be at the end of the document or anywhere within the text. However, there are some places within the HTML
text where scripts might not be interpreted or might be misinterpreted so use script tags within the document
body with caution. Here is a simple layout for an HTML Document with header and footer script tags
included. Type or cut and paste this template into your favorite text or HTML editor:
<HTML>
<HEAD>
<TITLE>My first Javascript Page</TITLE>
<BASE HREF='c:\website\htdocs'>
<SCRIPT>
//Your Javascript header script here
</SCRIPT>
</HEAD>
<BODY>
<!--This is the body of the HTML document. A document is like a
clean piece of paper on which you can write. Once the document
is written, you cannot change it. You have to take out a clean
piece of paper and rewrite it all. -->
</BODY>
<SCRIPT>
//Your Javascript footer script here
</SCRIPT>
</HTML>
Comments
The template given above has examples of both HTML comments and Javascript comments. HTML text
comments are placed like this:
<!-- your comments here -->
Javascript comments are similar to C comments; there are two ways to make them. You can either use
/*
Comment line one
Comment line two
Comment line ...
*/
which will do for either a single line or multiple lines of text, OR
//Comment line one
//Comment line two
//Comment line ...
"//" will only comment out the line of text on which it appears.
Debugging
Not a chance!
You can only debug with old-fashioned write line debugging, but there is no convenient debug window to
write lines to. You can, however use an alert box to visualize your debugging output. This is also a
way to provide feedback to your user. So here is your first Javascript script (we won't count the
comments):
<SCRIPT>
astr = 'My first Javascript script!\n'
bstr = 'The title of this document is ' + document.title + '\n'
cstr = 'This IS better than \"Hello World\".\n'
alert(astr + bstr + cstr)
</SCRIPT>
Put this script in a document header script of the skeleton given above and reload the document. As soon
as the document reloads, the alert box will pop up. Note that it does so before anything else is written, since
it is in the header. After you dismiss the alert box by clicking the OK button, the script finishes and the body
of the document is written.
Variables
Three variables (astr, bstr, cstr) were used to hold the text placed into the alert box. Think of variables as
containers which can hold text, numbers, or booleans (true/false). In many languages, variables are strongly
typed; i.e., you have to declare (which makes) the variable (container) and say what type it is before you can
use it. An analogy might be that you must buy a pie plate, which is designed specifically for pies, before
you can bake the pie. Javascript, like BASIC and Hypercard are untyped languages. That is, one container
fits all. Like a good plastic bag, you can put anything into it; the container loosely conforms to fit its
contents. Variables which hold text are called strings; variables which hold numbers are called numerics; and
variables which contain true/false values are called booleans. Although not foolproof, the Javascript
interpreter will try to figure out what you are doing and convert as necessary. Sometimes you need to help it
along, though. Try this between script tags in the template and reload the page.
<SCRIPT>
astr= 'The number is '
b = 6
c = 7
alert(astr + b + c)
alert(12 + b + c)
d = b + c
alert(astr + d)
</SCRIPT>
First, an alert box should pop up and say that the number is 67. Since the first item was a string, the
interpreter assumed concatenation and did not actually add 6 + 7. Once you dismiss the alert box, another
should pop up and give you the number 25. The interpreter now treats the variables as numerics, since they
could represent numbers and no strings are involved. Then a third box pops up and presents you with the
correct addition, since you did it separately. If, perchance, you would like two numbers to be concatenated
instead of added, concatenate them to the empty string, ''; e.g.,
Well, now that you know about alert boxes and variables, let's find a better use for a header script then
showing an alert box. Substitute the following for a header script in the simple document template and reload
the document.
<SCRIPT>
astr += '<TABLE BORDER=2 CELLPADDING=10 >'
astr += '<TR><TD>'
astr += '<FONT SIZE=7 COLOR="red">
bstr = document.title
cstr = '</B></FONT></TD></TR>'
cstr += '</TABLE>'
cstr += '</CENTER>'
dstr = '<HR><HR><BR>'
document.write(astr + bstr + cstr + dstr)
</SCRIPT>
You should see this at the top of your newly rewritten page, followed by the body text.
Now that's useful!
Paste this script into the header of a template document and Javascript will always write the header for you.
Just remember to define the title between title tags in the header PREVIOUS TO THE SCRIPT. Before we
close, let's go over the new items in the script. You should already be familiar with TABLE tags, FONT tags,
BReak tags and HR (horizontal rule) tags.
Operators
Javascript has the usual complement of mathematical operators such as +, - , * , and / . As you have seen, +
can also be used to concatenate strings. A new compound operator, += was introduced in this example.
Such operators are what cause C to be called "terse." Instead of saying
we say
There are many other operators, which you should review.
Document
The document is the blank page upon which your browser writes. It has a number of components (things
that it owns, like a title and a location ) and methods (things that it can do to itself, like open, close, and
write). The most used is document.write(something). The "something" can be a variable which
you have composed
astr = 'HELP!'
document.write(astr) //Do not put variables in quotes.
or a string literal
document.write('HELP!') // Put literals within quotes
or a combination
astr = 'HELP'
document.write(astr + 'ME!')
Nested Quotation Marks
In the script, we used this line
'<FONT SIZE=7 COLOR="red">'
For quotation marks, you can use either ' or ". If you need to quote something within a
quote, you must switch to the other form; i.e., you could have also used
"<FONT SIZE=7 COLOR='red'>"
If you need a third level of quotes, you may use \" (escaped quotation mark). Another escape sequence
commonly used is \n, which begins a new line.
Well, that's all for today. Already, you have learned how to significantly enhance your Web pages with
Javascript. Next time, we will learn how to put the header write code into a hidden frame as a Javascript
function, and we will enhance the header with more features. Most importantly, we will learn how to open a
new window under Javascript control.