Chapter 1 - The JavaScript Sourcebook | WebReference

Chapter 1 - The JavaScript Sourcebook

Chapter 1

What JavaScript Is All About



The HTML language used to create pages for the World Wide Web was originally designed to produce plain and static documents -- stuff like engineering notes and long-winded arguments by scientist types. When the Web first started the only browsing software available for it was text-based, so "plain and static" was acceptable.

The Web took a major step with the release of Mosaic, the first graphical Web browser. Suddenly, it was obvious to most everyone that "plain and static" wasn't enough. Users cried out for more creative control over the pages they published on the Web, which ushered in such features as in-line images, tables, and frames.

JavaScript continues the tradition of enhancing the Web by making HTML "come alive." As its name implies, JavaScript is a scripting language for HTML and the Netscape Navigator 2.0 (and later) browser. JavaScript "scripts" are small programs that interact with Netscape and the HTML content of a page. You can create a JavaScript program to add sound or simple animation, pre-validate a form before the user's response is sent to your company's server, search through a small database, set options based on user preferences, and much more.

JavaScript performs the same function as a macro in a word processor or electronic spreadsheet program. A macro is small program designed solely to run inside a program, and automate some task or to enhance a feature of the program. The difference here is that instead of a word processor or electronic spreadsheet application, JavaScript is designed for use with Netscape and surfing on the World Wide Web.

The Birth of JavaScript

JavaScript started life as "LiveScript." The concept of LiveScript began at Netscape, as they planned the features of their Netscape Navigator 2.0 product, released in January 1996. LiveScript was designed from the start to augment HTML pages, and Netscape planners saw it as a tool for the average Web page designer.

At first, interest in LiveScript was mild, due mostly to the frenzy surrounding a more robust Internet programming language, named Java. Java was developed over a three year period at Sun Microsystems, a company long entrenched in the Internet. Programmers flocked to Java because of its potential, at first leaving LiveScript in the cold.

When Netscape announced their intention of supporting Java in the Netscape 2.0 product, they also announced a collaboration with Sun on re-developing LiveScript, now renamed JavaScript. Suddenly, interest in the little "scripting language that could" blossomed. Whereas Java requires in-depth programming knowledge and a software development kit, JavaScript programs can be written by most any HTML page designer. No software development kit is needed.

As of this writing, JavaScript is used in Netscape 2.0 and above, as well as Microsoft Internet Explorer 3.0 and later. As the co-developers of JavaScript, Netscape has wanted to make JavaScript an "open standard," meaning that other companies can use and implement JavaScript in their own Internet products. When JavaScript was first announced in December of 1995, over two dozen companies jumped on the bandwagon promising to support it for future products. Those products -- from companies such as Microsoft, America Online, Borland, IBM, Symantec, and many others -- are just now coming out, or will be released shortly.



Why JavaScript is So Important? (and Why Should I Care?)

JavaScript is poised to do for Web publishing what Visual Basic did for Windows programming.



Uses for JavaScript

If you've spent much time on the Web you've probably encountered a few JavaScript examples. Probably the most popular use of JavaScript is as a calculator -- you know, the kind you can buy at Wal-Mart for $3.97. This application by no means indicates the full breadth and scope of JavaScript! Rather, JavaScript calculators spread because they are relatively easy to write. And Netscape's first JavaScript examples were calculators, so this is what pioneer JavaScripters emulated.

Feel free to write as many JavaScript calculators as you like, but don't limit JavaScript to just that. Like many things new, it can be hard to imagine practical uses for this new technology, called JavaScript. Here are some ideas that can get you started in thinking about what JavaScript can do for you.

Tailor Pages for the User

Imagine a Web page with JavaScript that responds to the user's choice of preferences, such as asking if the reader wants to view simple low-resolution thumbnail images for an entire page, or wait a little while longer for larger, high resolution images. Offering these and other custom interface choices helps you tailor your pages to the user's needs and preferences. Readers no longer all get the same page.

Make Interactive Pages

You can use JavaScript's built-in commands to add interactively to your Web pages. For instance, a JavaScript page can determine what time it is on the user's computer, and display the current time on the screen (see Figure 1-1). It can even select one of several images to display an appropriate graphic or background for the time of day -- a sunrise for morning, full sun for the day, a sunset for late afternoon, and the moon for evening.

<Figure 1-1. Interactivity is easy to do using JavaScript. A few simple lines of code can "personalize" your pages for users.>

Another great use of JavaScript for interactivity is conditionally displaying text and hypertext links, depending on the user's response to a query. Suppose, for example, your page contains descriptions of products for your company. You company makes lots of diverse products in various product lines. Rather than display text and hypertext links for products the user may not be interested in -- or worse, may confuse the reader -- you can use JavaScript to display only text and links that relate to the user's field of interest. This streamlines the content of Web pages.

JavaScript for Computer-Aided Instruction

You can easily use JavaScript for computer-aided instruction. A JavaScript page can be "smart"-- it can determine if the reader provides proper answers to questions, and can tally up the score. It can even keep track of how long it takes for a reader to answer questions. If your test has a time-limit, you can use JavaScript to automatically end the test when the limit is up.

The JavaScript Form Connection

JavaScript is also ideal for use with form-processing programs located on an Internet server. (For the uninitiated, a form is a collection of text boxes and buttons that provide for user feedback, much like a Windows or Macintosh dialog box provides for user feedback.) The traditional way to use forms on a Web page is to send all the user's entries to a "script" or program running on the computer, typically using a technique called common gateway interface, or CGI. The bulk of most any CGI program is verifying that the user entered valid data. Entry validation, like that shown in Figure 1-2, is something JavaScript can do, and it can do it very easily, thus making CGI programs much easier to write and implement.

<Figure 1-2. Form validation is a favorite application for JavaScript. The form can be pre-validating, before it is sent to a server for processing.>

Oh, Yes -- And Special Effects, Too!

An oft-cited use of JavaScript is for special effects. With JavaScript you can easily add sound to your page -- even background or repeating sound. Click a button, and a voice might ring out. Plus, there's lots you can do with animation, color effects, even "fading" a page slowly from black to white, like a movie.

JavaScript gives you greater control over the graphical elements of your page. For instance you can use JavaScript to intelligently resize an image. This is useful if you have a solid-color GIF. You can use JavaScript to expand or contract the size of the GIF, as it appears in Netscape. Possible uses: bar charts, colored divider lines (no more plain <HR> horizontal rules!), and more.

Using JavaScript in an HTML Document

A JavaScript program consists of one or more instructions (also referred to as code or commands) included with the HTML markup tags that form your Web documents. When Netscape encounters a JavaScript instruction, it stops to process it. For example, the instruction might tell Netscape to format and display text and graphics on the page. Unlike a program written in Java, JavaScript programs are not in separate files (though this is an option using Netscape 3.0 and later). Instead, the JavaScript instructions are mixed together with the familiar HTML markup tags you've come to love, like <H1>, <P>, <IMG> and the rest.

Consider the very basic HTML document. It renders a heading and some text on the page. Figure 1-3 shows how the page looks when viewed in Netscape.

<HTML>
<HEAD>
<TITLE>This Is a Basic Document</TITLE>
</HEAD>
<BODY>
<H1>This Is a Basic Document</H1>
<P>This is a pretty basic document.  It doesn't have much 
	of anything in it. Just a heading, and this text.</P>
</BODY>
</HTML> 

<Figure 1-3. A basic HTML document, as rendered in Netscape.>

Though there is no rational reason for doing so, you can use JavaScript to insert the text you see above. Here's how to use JavaScript to insert the heading.

<HTML>
<HEAD>
<TITLE>This Is a Basic Document</TITLE>
</HEAD>
<BODY>
<SCRIPT>
document.write ("<H1>This Is a Basic Document</H1>");
</SCRIPT>
<P>This is a pretty basic document.  It doesn't have much 
	of anything in it. Just a heading, this text, and 
	a graphic of some line.</P>
</BODY>
</HTML>

Trying the Script Yourself

Because JavaScript is embedded in the HTML document, you can most use any text editor or Web page editor to write your JavaScript programs. The only requirement is that the editor must allow direct input. Web page programs that only let you insert a given set of HTML markup tags cannot be used, because they don't allow you to insert the JavaScript code.

You can try the example to see how JavaScript works. Retype the example exactly as you see it. When done, save the document as sample.htm. Close the file (if necessary), and start Netscape. Choose File, Open, locate the file, and choose Open. It should look like Figure 1-4, above. Review your version if the document doesn't look at least something like it does it in the figure.

If you get an error box like that in Figure 1-5, it means you didn't properly type the text between the <SCRIPT> and </SCRIPT> tags. Carefully review your work and try again.

<Figure 1-4. The output results of the sample.htm document.>

<Figure 1-5. JavaScript displays an error message if it detects a problem in the code.>

The Role of the <SCRIPT> Tag

Netscape needs to be told that you're giving it JavaScript instructions, and these instructions are enclosed between <SCRIPT> tags. Within the script tag you can only have valid JavaScript instructions. You can't put HTML tags for Netscape to render inside the <SCRIPT> tags, and you can't put JavaScript instructions outside the <SCRIPT> tags. The following is allowed:

<HTML>
<BODY>
<H1>Here's JavaScript-generated text!</H1>
<SCRIPT>
document.write ("Hello there!");
</SCRIPT>
</BODY>
</HTML>

But these are not allowed:

<!--No script tags around the JavaScript instruction-->
<HTML>
<BODY>
<H1>Here's JavaScript-generated text!</H1>
document.write ("Hello there!");
</BODY>
</HTML>
<!--HTML markup tags inside the script tags -->
<HTML>
<BODY>
<H1>Here's JavaScript-generated text!</H1>
<SCRIPT>
<H1>Here's JavaScript-generated text!</H1>
document.write ("Hello there!");
<P>
</SCRIPT>
</BODY>
</HTML>
There may be other HTML scripting languages in the future, and the <SCRIPT> tag is designed to allow for differentiation in the language used. So, from here on in this book, the first instance of the <SCRIPT> tag in complete JavaScript programs in a document will also include the LANGUAGE="JavaScript" attribute. Example: <SCRIPT LANGUAGE="JavaScript"> Strictly speaking this attribute is optional, but we'll include it for the sake of completeness.

A Realistic Use of JavaScript

Obviously, you don't use JavaScript to insert the text that HTML can otherwise do all by itself. I used the example above because it's simple and demonstrates the basic JavaScript concept of embedded scripts in an HTML page.

JavaScript is ideal for making your Web pages "smart." Here's an example. Suppose you want to change the graphic depending on whether it's day or night. JavaScript has a rich selection of date-oriented functions, one of which returns the current hour, as set by the user's computer. Here's how that basic document uses JavaScript instructions to programmatically select the right GIF for the time of day:

<HTML>
<HEAD>
<TITLE>This Is a Basic Document</TITLE>
</HEAD>
<BODY>
<H1>This Is a Basic Document</H1>
<P>This is a pretty basic document.  It doesn't have much 
	of anything in it. Just a heading, this text, and 
	a graphic of some line.</P>
<SCRIPT>
now = new Date();
if ((now.getHours() > 5) && (now.getHours()<18))
	document.write ("<IMG SRC='https://mydoamin.com/day.gif'>");
else
	document.write ("<IMG SRC='https://mydomain.com/night.gif'>");
</SCRIPT>
</BODY>
</HTML>

This example uses a JavaScript if statement to determine if the time of day. The if statement does one thing if the expression is true, or does another if the expression is false. If the hour is greater than 5 am, but less than 6pm, it's daylight (see Figure 1-6). So, JavaScript inserts an image (<IMG>) tag using the DAY.GIF image. If the current is not between these hours, it night time, so JavaScript insert the NIGHT.GIF image.

<Figure 1-6. Use JavaScript to conditionally display a n image depending on the of day.>

HTML alone lacks any decision-making, so this example is a perfect job for JavaScript. The page contains the basic HTML tags to render the document, and JavaScript for any tasks that require "thinking."

Viewing JavaScript "Objectively"

You've probably heard of object oriented programming. It's a style of programming where software is created using self-contained modules. Each module is designed to take a certain type of data, and do something with it. The term "object oriented" comes from how the data is viewed: as an object. While object oriented programming is more difficult than the traditional "precedural" programming (like Basic and C), the end result is usually easier to maintain and fix. Almost all major software products released today are written using object oriented techniques.

JavaScript uses objects but it is not an object oriented programming language. It's strictly procedural, which means you don't have to learn anything about object oriented programming (if you did this book would be over twice the size). Objects are used in JavaScript to represent "things." The document as viewed in the Netscape browser is a "thing." The fill-in form that you see on the browser page is a "thing." The hypertext link you click on to go to another URL is a "thing."

These things -- er, objects -- are best viewed as a total entity to make programming easier. Objects are composed of properties, which is stuff that belongs to that object. As in real life, not all objects have the same properties. Imagine a window. That's an object. Now imagine that window having a property for open/closed (the one property can represent both states).

Now imagine the lamp by your desk. It's an object too, but it doesn't have an open/closed property. Instead, it has an on/off property. Each property is contextually relevant to its object. This is an important concept.

A good example of a JavaScript object is the document that you view in the Netscape window. The document has many properties, including the background color, the text color, and the title. When you work with JavaScript, you uniquely identify the properties you want as belonging to a certain object. You don't just say "change the color of the background to green"; JavaScript won't have the slightest idea what you're talking about. What background? Rather, to change the background of the document, you must specify the document object.

JavaScript's uses a special syntax for the object-property relationship. You use the object name (in this case document), a period, and the property name, which is bgColor. Put 'em together and you have:

document.bgColor

This is enough to tell JavaScript what object you want to work with, and what property of that object you want to change or test. For example, want to change the background of the document? That's easy. The following instruction changes the background color to black:

document.bgColor = "black";

Test this for yourself Here's a short script that sets the background according to the time of day. It uses document.bgColor to set the background color, and fgColor to set the foreground (text) color. The page is rendered black-on-white for the daytime, and white-on-black for the nighttime. I'll use the color names for this example, rather than the #nnnnnn color triplet values you may be used to. Both are valid with Netscape.

bgsetter.html
<CD>
<HTML>
<HEAD>
<TITLE>This Is a Basic Document</TITLE>
<SCRIPT LANGUAGE="JavaScript">
now = new Date();
if ((now.getHours() > 5) && (now.getHours()<18)) {
	document.bgColor = "white"; 
	document.fgColor = "black";
} else {
	document.bgColor = "black"; 
	document.fgColor = "white";
}
</SCRIPT>
</HEAD>
<BODY>
<H1>This Is a Basic Document</H1>
<P>This is a pretty basic document.  It doesn't have much 
	of anything in it. Just a heading, this text, and 
	a graphic of some line.</P>
</BODY>
</HTML>

When you retype this, be very sure to check all of your work. Don't forget the { and } brace characters for the if statement. Netscape will display an error message if these are missing. (For the curious, the braces are needed in this example because more than one line of code follows the if statement.) Placement of the <SCRIPT> tags can make a difference. You can change the background property of the document at any time, even after the page has been rendered in the browser (this applies to the Windows platforms only when using Netscape 2.0; bugs in the Macintosh and X-Windows platforms cause the text to be obliterated when the background changes). However, the same doesn't apply to the foreground (text) property. You can change the property, but only before the text is rendered in the browser. Therefore, putting the <SCRIPT> tag after the text will not yield proper results. Keep this in mind when writing your JavaScript programs.

A Method to Its Madness

Closely related to objects are methods. A method is something you can do with an object. Like properties, methods are contextually tied with the object they belong to, and not all objects have the same methods. Think of a method as an action that causes the object to change or respond in some way. Consider that window and desk lamp again. A valid method for the window might be to open and close it. A valid method for the lamp might be to turn it off an on.

You've already seen a JavaScript method at work: document.write. Write is a method of the document object. It causes JavaScript to send HTML output to the document. Whenever you want to insert text or tags in the document, use document.write. Similarly, there are methods for the document property to open a new document, to close a document, and much more.

In many ways, methods can be considered JavaScript "commands," as they cause something to happen to an object. There are dozens of methods, each one contextually related to the object it serves. Adding to this canopy of choices are a very small sprinkling of JavaScript functions. Unlike methods, however, functions are unlike methods in that they are not intrinsically tied to an object. For example, a commonly used JavaScript function is parseInt, used in converting number formats.

Statements Tie It All Together

Statements are programming commands. You've already been introduced to the if statement. There are others, including return, var, while, and for. Statements are used to construct the thinking and doing portion of your JavaScript programs.

JavaScript currently supports few statements -- about a dozen -- but more will come as the language matures. With new statements come additional capabilities. This doesn't mean JavaScript is anemic when it comes to programming prowess. On the contrary, with a bit of ingenuity and imagination you can construct very complex programs, even with limited a selection of statements JavaScript offers.


Comments are welcome

Copyright © 1996 Gordon McComb and
Revised: October 16, 1996

URL: https://webreference.com/content/jssource/