Brought to you by EarthWeb
IT Library Logo

Click Here!
Click Here!


Search the site:
 
EXPERT SEARCH -----
Programming Languages
Databases
Security
Web Services
Network Services
Middleware
Components
Operating Systems
User Interfaces
Groupware & Collaboration
Content Management
Productivity Applications
Hardware
Fun & Games

EarthWeb Direct EarthWeb Direct Fatbrain Auctions Support Source Answers

EarthWeb sites
Crossnodes
Datamation
Developer.com
DICE
EarthWeb.com
EarthWeb Direct
ERP Hub
Gamelan
GoCertify.com
HTMLGoodies
Intranet Journal
IT Knowledge
IT Library
JavaGoodies
JARS
JavaScripts.com
open source IT
RoadCoders
Y2K Info


Chapter 2

Your First Script


CONTENTS


In this chapter, you finally get down to the details of producing a JavaScript script.

You learn about the following topics, which will lead to your first complete JavaScript script:

  • How to incorporate JavaScript into HTML
  • Command and command block structure in JavaScript
  • Output functions

You then learn how to use JavaScript scripts to create text output that is directed to the client window, in sequence with an HTML file, and then is interpreted just like regular HTML.

Of course, this doesn't really allow you to do anything with JavaScript that you can't already do with HTML. So, as the chapter continues, you will take the next step: generating output in dialog boxes, as opposed to putting it on the Web page itself, and generating dynamic output that can change each time the page is loaded.

We cover the following topics:

  • Creating output in a dialog box using the alert() method
  • Prompting users for input in a dialog box using the prompt() method
  • Displaying dynamic output by combining the prompt method with document.write() and document.writeln()

Incorporating JavaScript into HTML

At the present time, all JavaScript scripts need to be included as an integral part of an HTML document. To do this, Netscape has implemented an extension to standard HTML: the SCRIPT tag.

The SCRIPT Tag

Including scripts in HTML is simple. Every script must be contained inside a SCRIPT container tag. In other words, an opening <SCRIPT> tag starts the script and a closing
</SCRIPT> tag ends it:

<SCRIPT>

JavaScript program

</SCRIPT>

The SCRIPT tag takes two optional attributes which determine how the JavaScript script in question is incorporated into the HTML file. These attributes are outlined in Table 2.1.

Table 2.1. Attributes for the SCRIPT tag.

AttributeDescription
SRC URL for a file containing the JavaScript source code. The file should have the extension .js. See Navigator's Web site for more details on the SRC tag.
LANGUAGE Indicates the language used in the script. In the current version of Navigator this attribute can take only two values: JavaScript and LiveScript. LiveScript is provided for backward compatibility with early scripts developed when the language was called LiveScript. You should use JavaScript in your scripts.

Note
Using the SCRIPT tag and its attributes allows you to use two techniques to integrate a JavaScript program into an HTML file. In Navigator, however, programmers have only one choice: to include their JavaScript programs in their HTML files.

Tip
Although Navigator supports the use of LANGUAGE="LiveScript" for backward compatibility, this will be dropped in future versions of the browser. It is best to use LANGUAGE="JavaScript". In addition, LANGUAGE="LiveScript" is not compatible with Microsoft's Internet Explorer 3.0.

Including JavaScript in an HTML File

The first, and easiest, way is to include the actual source code in the HTML file, using the following syntax:

<SCRIPT LANGUAGE="JavaScript">

JavaScript program

</SCRIPT>

Hiding Scripts from Other Browsers

Of course, an immediate problem crops up with this type of SCRIPT container: Browsers that don't support JavaScript will happily attempt to display or parse the content of the script. In order to avoid this, Netscape recommends the following approach using HTML comments:

<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE THE SCRIPT FROM OTHER BROWSERS

JavaScript program

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>

These comments (<!-- HIDE THE SCRIPT FROM OTHER BROWSERS and // STOP HIDING FROM OTHER BROWSERS -->) ensure that other Web browsers will ignore the entire script and not display it because everything between <!-- and --> should be ignored by a standard Web browser. Of course, if users were to view the source code of the document, they would still see the script.

Problems with the SCRIPT Tag

This technique of combining the SCRIPT container tag with comments isn't foolproof, however. Right now, the SCRIPT tag is not an accepted part of the HTML 2.0 standard and the HTML 3.0 specification is incomplete. For the time being, competing browser makers could use the SCRIPT tag for another purpose.

Note
At press time, it looked as though the SCRIPT tag, and possibly JavaScript itself, would become part of the HTML 3.0 specification because it is backed by Netscape and Sun, among others.

In fact, with Netscape Navigator 2.0, the latter problem has already occurred with the implementation of frames. Among several tags used to produce frames, Netscape uses a FRAME tag that is used by IBM's Web Explorer for another purpose.

In addition, by hiding the script from other browsers, users of these other browsers will be unaware of the script's existence. One solution to this problem could be to use the following approach:

<SCRIPT LANGUAGE="JavaScript">

// JavaScript Script appears Here<BR>
// Download Netscape Navigator to use it.

<!-- HIDING FROM OTHER BROWSERS

JavaScript Program

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>

Note
Unlike HTML, which creates comments with the structure <!-- Comments Here -->, JavaScript comments start with a double-slash (//) anywhere on the line and continue to the end of the line. If not contained within an HTML comment structure, a JavaScript comment will be displayed by non-Netscape browsers. As you learn later in this chapter, JavaScript also includes multiline comments.

Stating with Navigator 3, Netscape has introduced the NOSCRIPT which provides a way for alternative text to be specified for non-JavaScript browsers. Any text between NOSCRIPT tags will be displayed by other browsers, but Navigator 3 will ignore it. The previous example could be implemented using the NOSCRIPT tag:

<SCRIPT LANGUAGE="JavaScript">
<!-- HIDING FROM OTHER BROWSERS

JavaScript Program

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>

<NOSCRIPT>

JavaScript Script appears Here<BR>
Download Netscape Navigator 2.0 to use it.

</NOSCRIPT>

Where to Put Your JavaScript Code

JavaScript scripts and programs can be included anywhere in the header or body of an HTML file. Many of the examples on Netscape's Web site, as well as elsewhere, make it a habit to include the SCRIPT container in the header of the HTML file, and this is the preferred format.

Still, other developers prefer to include the JavaScript program next to the element or section of the HTML it refers to, such as a form. Because an HTML file can contain more than one SCRIPT tag, it is possible to place JavaScript functions in logical places in a file for ease of coding and debugging.

As you will see in Chapter 4, "Functions and Objects-The Building Blocks of Programs," there are compelling reasons to put certain segments of your JavaScript code in the header of the HTML file to ensure they are evaluated before users can initiate events.

Using External Files for JavaScript Programs

While including JavaScript programs directly in HTML files can be convenient for small scripts and basic HTML pages, it can quickly get out of hand when pages require long and complex scripts.

To make development and maintenance of HTML files and JavaScript scripts easier, the JavaScript specification includes the option of keeping your JavaScript scripts in separate files and using the SRC attribute of the SCRIPT tag to include the JavaScript program in an HTML file.

In its simplest form, the SRC construct can be used like this:

<SCRIPT LANGUAGE="JavaScript" SRC="http://www.you.com/JavaScript.js">
</SCRIPT>

Note
For the SRC attribute to work, the name of the JavaScript source files should include the extension .js. In addition, your Web server needs to be configured with the correct file type for JavaScript files. Information about this is available on Netscape's Web site.

One of the benefits of this approach is that your scripts are automatically hidden from other browsers that don't support JavaScript. At the same time, though, this technique requires an additional server request and server access, which may be problematic on a slow server or across a slow connection to the Internet.

In addition, both techniques (JavaScript code in an HTML file and JavaScript code in an external file) can be used at the same time. You can do this with a single SCRIPT container or more than one:

<SCRIPT LANGAUGE="JavaScript" SRC="http://www.you.com/JavaScript.js">
<!-- HIDE FROM OTHER BROWSERS

More JavaScript code

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>

or

<SCRIPT LANGUAGE="JavaScript" SRC="http://www.you.com/JavaScript.js">
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS

More JavaScript code

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>

Listing 2.1 demonstrates a simple JavaScript script inside an HTML file.


Listing 2.1. Including a program in an HTML file.
<HTML>

<HEAD>
<TITLE>Listing 2.1</TITLE>
</HEAD>

<BODY>
Here's the result:

<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS

// Output "It Works!"
document.writeln("It works!<BR>");

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>

</BODY>
</HTML>

This HTML file produces results similar to those in Figure 2.1. By comparison, using a browser that doesn't support JavaScript (such as ncSA Mosaic), the results look like those in Figure 2.2.

Figure 2.1 : In Navigator, the output displays in source code order.

Figure 2.2 : Part of the script is hidden when JavaScript is unsupported.

The script in Listing 2.1 demonstrates several important points which will become clear in later chapters.

First, it is possible to generate dynamic HTML output at the time of document loading using JavaScript scripts. Second, nothing in the script is displayed on other browsers even though the rest of the HTML file loads and displays without any difficulty. To compare, delete the HTML comment lines, and the output looks like Figure 2.3. You can see that the entire JavaScript command document.writeln("It Works!<BR>"); has been displayed, and the <BR> tag has been interpreted by the non-JavaScript browser.

Figure 2.3 : Without the HTML comments the JavaScript code displays.

In this example, you also see how JavaScript comments work. The line that begins with two slashes,

// Output "It Works!"

is a single-line JavaScript comment similar to those used in C++. Everything after the // until the end of the line is a comment. JavaScript also supports C-style multiline comments, which start with /* and end with */:

/* This
   is
   a
   comment */

Comments are useful to help other people read your programs and understand what different commands and functions are doing. In addition, when you write long or complex programs, liberal use of meaningful comments will help you understand your own program if you come back to alter it after an extended period of time.

Basic Command Syntax

The basic syntax and structure of JavaScript looks familiar to anyone who has used C, C++, or Java. A JavaScript program is built with functions (covered in Chapter 4) and statements, operators, and expressions. The basic command unit is a one-line command or expression followed by an optional semicolon; for example:

document.writeln("It Works!<BR>");

This command invokes the writeln() method, which is part of the document object. The semicolon indicates the end of the command.

Note
JavaScript commands can span multiple lines. Multiple commands can also appear on a single line, as long as the semicolon is there to mark the end of each command. In fact, except where it is essential to distinguish between commands, the semicolon is optional. I use it throughout this book to make source code clearer and easier to read.

Command Blocks

Multiple commands can be combined into command blocks using curly braces ({ and }). Command blocks are used to group together sets of JavaScript commands into a single unit, which can then be used for a variety of purposes, including loops and defining functions. (These subjects will be discussed in later chapters.) A simple command block looks like this:

{
  document.writeln("Does it work? ");
  document.writeln("It works!<BR>");
}
Command blocks can be embedded, as the following lines illustrate.
{
  JavaScript code

  {

    More JavaScript code

  }

}

When you embed command blocks like this, it is important to remember that all open curly braces must be closed and that the first closing brace closes the last opened curly brace. In the following example, the first } closes the second { as shown by the | markers:

{
| JavaScript code
|
| {
| |
| | More JavaScript code
| |
| }
|
}

Tip
When embedding command blocks inside each other, it is common practice to indent each successive command block so that it's easy to identify where blocks start and end when reading program code. Extra spaces and tabs don't have any effect on JavaScript programs.

In JavaScript, object, property, and method names are case sensitive, as are all keywords, operators, and variable names. You learn about operators and variables in Chapter 3, "Working with Data and Information." In this way, all the following commands are different (and some are illegal):

document.writeln("Test");
Document.Writeln("Test");
document.WriteLN("Test");

Outputting Text

In most programming languages, one of the basic capabilities is to output-or display-text. In JavaScript output can be directed to several places including the current document window and pop-up dialog boxes.

Output in the Client Window

In JavaScript, programmers can direct output to the client window in sequence with the HTML file. As discussed in the previous section, JavaScript that produces output is evaluated where it occurs in the HTML file, and the resulting text is interpreted as HTML for the purpose of displaying the page.

In addition to this, JavaScript allows programmers to generate alert and confirm boxes that include text and one or two buttons. Text and numbers can also be displayed in TEXT and TEXTAREA fields in a form.

In the following sections, you look at outputting text to the document window.

The document.write() and document.writeln() Methods

The document object in JavaScript includes two methods designed for outputting text to the client window: write() and writeln(). In JavaScript, methods are called by combining the object name with the method name:

object-name.property-name

Data that the method needs to perform its job is provided as an argument in the parentheses, for example:

document.write("Test");
document.writeln('Test');

Arguments are data provided to a function or a method for use in its calculations and processing. They are provided (or passed) to the function or method by listing them in the parentheses following the function or method name. Multiple arguments are separated by commas.

Note
A quick look at these examples shows you that strings of text are surrounded by double (or single) quotes and that the two methods (document.write() and document.writeln()) are invoked in the same manner. Open and close quotes must be of the same type-you cannot open with double quotes and close with single quotes or vice versa.

The write() method outputs text and HTML as a string of text to the current window in sequence with the current HTML file. Because the SCRIPT container does not affect the HTML structures where it occurs, any format tags or other elements in the HTML file will affect the text and HTML produced by the write() method. For example, Listing 2.2 produces output like Figure 2.4.


Listing 2.2. Outputting HTML tags from JavaScript.
<HTML>

<HEAD>
<TITLE>Ouputting Text</TITLE>
</HEAD>

<BODY>
This text is plain.<BR>
<B>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS

document.write("This text is bold.</B>");

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>

</BODY>

</HTML>

Figure 2.4. shows the resulting effect:

Listing 2.2 also demonstrates that HTML tags, as well as regular text, can be output by the write() method. You will notice that the <B> and </B> tags can either be output as part of the write() method or left outside the script. In either case, the text and HTML is evaluated in the order it appears in the complete HTML and JavaScript source code.

The writeln() method is the same as the write() method except that it adds a carriage return at the end of the string that is being output. This is really only relevant inside of PRE and XMP containers where carriage returns are interpreted in displaying the text. Listing 2.3 shows an example of the writeln() method.


Listing 2.3. Using the writeln() method with the PRE tag.

<PRE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS

document.writeln("One,");
document.writeln("Two,");
document.write("Three ");
document.write("...");

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</PRE>

This example produces results like those in Figure 2.5.

Figure 2.5 : Output using the writeln() method.

In JavaScript, strings of text, such as those used to produce output with the write() and writeln() methods, can include special keystrokes to represent characters that can't be typed, such as new lines, tabs, and carriage returns. The special characters are reviewed in Table 2.2.

Table 2.2. Special characters in strings.

Character
Description
\n
new line
\t
tab
\r
carriage return
\f
form feed
\b
backspace

For example, the following command displays the text "It Works!" followed by a new line:

document.write("It Works!\n");

All special characters start with a backslash (\). This is called escaping characters. Escaping a character is used in many scripting and programming languages to represent a character that cannot be typed or that has special meaning in the language and would be interpreted incorrectly if left unescaped.

A perfect example of this is the backslash itself. In order to output a backslash in JavaScript, it is necessary to escape the backslash:

document.write("A backslash: \\");

In this example, the first backslash tells JavaScript that the next character is a special character and not to treat it normally. In this case it outputs a backslash rather than treating the second backslash in the normal way (as the escape character).

Listing 2.4 is a variation on the traditional Hello World program that most students learn as their first program in a new programming language. Instead of simply outputting "Hello World!" to the display window, you are going to produce the entire output using JavaScript and include a GIF image along with the phrase "Welcome to Netscape Navigator." The GIF is included with the source code on the enclosed CD-ROM.


Listing 2.4. Welcome to Netscape Navigator.
<HTML>

<HEAD>
<TITLE>Example 2.4</TITLE>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS

document.write('<IMG SRC="welcome.gif">');
document.write("<BR><H1>Welcome to Netscape Navigator</H1>");

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</BODY>

</HTML>

This script produces output like that in Figure 2.6.

Figure 2.6 : JavaScript can be used to generate complete HTML output.

In this example, you can see how both text and HTML tags can be output to the current HTML windows using the write() method. Notice the use of both single quotes and double quotes to delimit the start and end of the text strings. In the first call to the write() method, you use the single quotes so that the text string can contain the double quotes required by the IMG tag.

Stepping Beyond the Document Window

One of the restrictions of HTML has always been that Web site developers have been limited to a single client window. Even with the appearance of frames and the TARGET tag in Navigator, authors are still constrained to displaying HTML files in complete browser windows and are unable to direct small messages to the user through another window without having the message become part of an HTML page.

Working with Dialog Boxes

JavaScript provides the ability for programmers to generate output in small dialog boxes-the content of the dialog box is independent of the HTML page containing the JavaScript script and doesn't affect the appearance or content of the page.

The simplest way to direct output to a dialog box is to use the alert() method. To use the alert() method, you just need to provide a single string of text as you did with document.write() and document.writeln() in the previous section:

alert("Click OK to continue.");

Note
You will notice that the alert() method doesn't have an object name in front of it. This is because the alert() method is part of the window object. As the top-level object in the Navigator Object Hierarchy, the window object is assumed when it isn't specified.

The preceding command generates output similar to Figure 2.7. The alert dialog box displays the message passed to it in parentheses, as well as an OK button. The script and HTML holding the script will not continue evaluating or executing until the user clicks the OK button.

Figure 2.7 : Alert dialog boxes display a message along with an OK button to continue.

Generally, the alert() method is used for exactly that-to warn the user or alert him or her to something. Examples of this type of use include:

  • Incorrect information in a form
  • An invalid result from a calculation
  • A warning that a service is not available on a given date

Nonetheless, the alert() method can still be used for friendlier messages.

Note
Notice that JavaScript alert boxes include the phrase "JavaScript Alert" at the start of the message. All dialog boxes generated by scripts have similar headings in order to distinguish them from those generated by the operating system or the browser. This is done for security reasons so that malicious programs cannot trick users into doing things they don't want to do. Netscape designers have indicated that they may make dialog boxes generated by scripts visually different in future versions.

Next, take the preceding example, Listing 2.4, "Welcome to Netscape Navigator", and have the message display in an alert box. To do this, you need to make only a small change in your original script, as shown in Listing 2.5:


Listing 2.5. Displaying a message in an alert box.
<HTML>

<HEAD>
<TITLE>Example 2.5</TITLE>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS


alert("Welcome to Netscape Navigator");
document.write('<IMG SRC="welcome.gif">');

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</BODY>

</HTML>

Figures 2.8 and 2.9 show the progression of events with this script.

Figure 2.8 : The alert dialog box is displayed first.

Figure 2.9 : After OK is clicked, the rest of the script executes.

Notice in this example, you have reversed the order of the message and the graphic. This way, the user will see the message in a dialog box and the graphic will not load until OK has been clicked.

Note
The alert() method produces different results on different platforms. On Windows versions of Netscape Navigator, script processing and parsing of HTML files waits until the user clicks on the OK button. On UNIX versions Navigator, the alert box will be displayed and the script will continue processing and the rest of the HTML will be interpreted regardless of when the user clicks on OK.

As with document.write(), you can use special characters, such as \n, in the alert message to control the formatting of the text displayed in the dialog box. The following command would generate an alert box similar to the one in Figure 2.10:

Figure 2.10 : By using special characters, you can format text in dialog boxes.

alert("Welcome!\n\n\tYou are using Netscape Navigator");

Interacting with the User

The alert() method still doesn't enable you to interact with the user. The addition of the OK button provides you with some control over the timing of events, but it still cannot be used to generate any dynamic output or customize output based on user input.

The simplest way to interact with the user is with the prompt() method. Like alert(), prompt() creates a dialog box with the message you specify, but it also provides a single entry field with a default entry. The user needs to fill in the field and then click OK. An example of the prompt() method is the following line, which generates a dialog box like the one in Figure 2.11:

Figure 2.11 : The prompt dialog box includes a message and an entry field along with an OK button and a Cancel button.

prompt("Enter Your favourite color:","Blue");

You will immediately notice a difference with the way you used the alert() method: You are providing two strings to the method in the parentheses. The prompt() method requires two pieces of information: The first is text to be displayed, and the second is the default data in the entry field.

Note
The pieces of information provided in parentheses to a method or function are known as arguments. In JavaScript, when a method requires more than one argument, they are separated by commas.

You might have noticed that if used by itself, the prompt() method accepts input from the user, but the information is essentially lost. This is solved by realizing that methods and functions can return results, as mentioned in the previous chapter. That means that the prompt() method will return the user's input as its result.

The result returned by a method can be stored in a variable (which you will learn about in the next chapter) or can be used as an argument to another method:

document.write("Your favorite color is: ");
document.writeln(prompt("Enter your favorite color:","Blue"));

In the second line of this code segment, the document.writeln() method displays the results returned by the prompt() method as illustrated by Figures 2.12 and 2.13.

Figure 2.12 : The prompt() method can be used to ask the user questions.

Figure 2.13 : Based on the answers, dynamic content can be created.

Using the prompt() method, you are now in a position to generate a personalized version of the "Welcome to Netscape Navigator" example you have been working with. Listing 2.6 shows the new program.


Listing 2.6. The revised welcome program.
<HTML>

<HEAD>
<TITLE>Example 2.6</TITLE>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS

document.write('<IMG SRC="welcome.gif">');
document.write("<H1>Greetings, ");
document.write(prompt("Enter Your Name:","Name"));
document.write(". Welcome to Netscape Navigator</H1>");

// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</BODY>

</HTML>

This script first displays the welcome graphic and the word "Greetings" in the Navigator window. Then, a prompt dialog box asks for the user's name and once this is entered the sentence is completed and displayed with the user's name following "Greetings."

In this example, you have used the prompt() method to construct a personalized welcome greeting. However, notice that the process was somewhat cumbersome, requiring four document.write() commands to display what could easily be two short lines in HTML.

This can be made a little easier by combining multiple strings of text into a single string of text using what is known as concatenation.

Concatenation is discussed in more depth in Chapter 3. Using concatenation, multiple strings are combined into a single string and are treated as a single string by JavaScript.

In order to do this, you can combine the various pieces of your welcome message into a single document.write() command using a simple plus sign (+):

document.write('<IMG SRC="welcome.gif">');
document.write("<H1>Greetings, " + prompt("<BR>Enter Your Name:","Name") +
  ". Welcome to Netscape Navigator</H1>");

Summary

In this chapter you learned how to combine JavaScript scripts into HTML files using the SCRIPT tag. The SCRIPT tag can also be used to include JavaScript code kept in separate external files. Multiple SCRIPT containers can be used in a single HTML file. You also learned the basic structure of JavaScript commands and how to use curly braces to build blocks of multiple commands.

We also took a look at how to use the write() and writeln() methods which are part of the document object, as well as reviewed the special characters which can be used when outputting text. In addition, you learned the syntax of JavaScript comments.

In this chapter you also moved beyond static output limited to the current client window.

Using the alert() method, it is possible to direct output from a JavaScript script to a dialog box. This can be taken a step further with the prompt() method.

The prompt() method enables you to ask the user to enter a single item of data in an entry field in a dialog box. The data the user enters is returned by the prompt() method and can be output using document.write() or document.writeln(). This is one way you can generate dynamic, custom output in a Web page.

Commands and Extensions Review

Command/ExtensionType Description
SCRIPT HTML tagContainer for JavaScript scripts.
SRC SCRIPT attribute Holds the URL of an external JavaScript file. External files must have the extension .js. (Not yet implemented; optional.)
LANGUAGE SCRIPT attribute Specifies the language of the script. Currently, the only valid values for this attribute are LiveScript and JavaScript. (optional)
// JavaScript commentStart of a single-line comment. Comment starts with // and ends at the end of the line.
/* ... */ JavaScript commentJavaScript multiline comments start with /* and end with */.
document.write() JavaScript methodOutputs string to the current window in sequence with HTML file containing the script.
document.writeln() JavaScript methodOutputs string to current document followed by a carriage return.
alert() JavaScript methodDisplays a message in a dialog box.
prompt() JavaScript methodDisplays a message in a dialog box and provides a single input field for the user to enter a response to the message.

Exercises

  1. Change Listing 2.4 so that it produces output in preformatted text (using HTML's PRE tag) with "Welcome to" and "Netscape Navigator" on separate lines.
  2. How would you rewrite the example from exercise question 1 using only one write() or writeln() command?
  3. How would you customize the output in Listing 2.5 to include the user's name?
  4. Try entering the following in the prompt dialog box generated by the script from Listing 2.6 and see what happens:
    • Press Cancel instead of OK.
    • Enter text that includes some simple HTML tags, such as John<BR>Doe.
    • Enter text that contains special characters such as John\nDoe.
What do you learn from the results?

Answers

  1. The following code uses the writeln() method to produce the desired result:

    <HTML>

    <HEAD>
    <TITLE>Welcome to Netscape Navigator!</TITLE>
    </HEAD>

    <BODY>

    <SCRIPT LANGUAGE="JavaScript">
    <!-- HIDE FROM OTHER BROWSERS

    document.write('<IMG SRC="welcome.gif">');
    document.writeln("<BR><PRE>Welcome to");
    document.write("Netscape Navigator</PRE>");

    // STOP HIDING FROM OTHER BROWSERS -->
    </SCRIPT>

    </BODY>

    </HTML>
  2. Using the \n special character, it is possible to produce the same results as the previous exercise question using only one call to the write() method:

    <HTML>

    <HEAD>
    <TITLE>Welcome to Netscape Navigator</TITLE>
    </HEAD>

    <BODY>

    <SCRIPT LANGUAGE="JavaScript">
    <!-- HIDE FROM OTHER BROWSERS

    document.write('<IMG SRC="welcome.gif"><BR><PRE>Welcome to\nNetscape
    Â Navigator </PRE>');
    // STOP HIDING FROM OTHER BROWSERS -->
    </SCRIPT>

    </BODY>

    </HTML>    
  3. The following example customizes the script from Listing 2.5 to include the user's name:

    <HTML>

    <HEAD>
    <TITLE>Exercise 2.3</TITLE>
    </HEAD>

    <BODY>
    <SCRIPT LANGUAGE="JavaScript">
    <!-- HIDE FROM OTHER BROWSERS

    alert("Greetings, " + prompt("Enter Your Name:","Name") + ".\nWelcome to
    Â Netscape Navigator");
    document.write('<IMG SRC="welcome.gif">');

    // STOP HIDING FROM OTHER BROWSERS -->
    </SCRIPT>
    </BODY>

    </HTML>
  4. You learn several things from the tests in this exercise:
    • Clicking on Cancel returns a value of null. You learn about the null value in Chapter 3.
    • HTML tags entered by the user are interpreted by the Web browser before displaying the text on the page.
    • Special characters entered in a string returned by the prompt() method are not evaluated but are just displayed as plain text. In this way, if the user types \n, it will be displayed as \n rather than being evaluated to a new line.



footer nav
Use of this site is subject certain Terms & Conditions.
Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details.