|
|||
|
Click Here! |
Chapter 2Your 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:
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:
Incorporating JavaScript into HTMLAt 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>
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.
Including JavaScript in an HTML FileThe first, and easiest, way is to include the actual source code in the HTML file, using the following syntax: <SCRIPT LANGUAGE="JavaScript"> Hiding Scripts from Other BrowsersOf 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"> 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.
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">
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"> Where to Put Your JavaScript CodeJavaScript 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 ProgramsWhile 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">
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"> or <SCRIPT LANGUAGE="JavaScript" SRC="http://www.you.com/JavaScript.js"> Listing 2.1 demonstrates a simple JavaScript script inside an HTML file.
Listing 2.1. Including a program in an HTML file. <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.
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 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 SyntaxThe 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.
Command BlocksMultiple 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: { 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: {
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"); Outputting TextIn 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 WindowIn 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() MethodsThe 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");
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>
Figure 2.4. shows the resulting effect:
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>
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.
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>
This script produces output like that in Figure 2.6.
Figure 2.6 : JavaScript can be used to generate complete HTML output.
Stepping Beyond the Document WindowOne 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 BoxesJavaScript 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.");
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:
Nonetheless, the alert()
method can still be used for friendlier messages.
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>
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.
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 UserThe 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: 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.
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: "); 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>
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."
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.
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">'); SummaryIn 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/Extension | Type | Description |
SCRIPT | HTML tag | Container 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 comment | Start of a single-line comment. Comment starts with // and ends at the end of the line. |
/* ... */ | JavaScript comment | JavaScript multiline comments start with /* and end with */. |
document.write() | JavaScript method | Outputs string to the current window in sequence with HTML file containing the script. |
document.writeln() | JavaScript method | Outputs string to current document followed by a carriage return. |
alert() | JavaScript method | Displays a message in a dialog box. |
prompt() | JavaScript method | Displays a message in a dialog box and provides a single input field for the user to enter a response to the message. |
What do you learn from the results?
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. |