Notice: This material is excerpted from Special Edition Using JavaScript, ISBN: 0-7897-0789-6. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.
Remember the thrill of creating your first Web page and clicking your first hyperlink to another site? The excitement of surfing from California to Maine, from Australia to Finland? This interactive nature of the Web attracts millions of people to the Web every day.
With JavaScript, new dynamic elements let you go beyond the simple click and wait. Users will not just read your pages but also interact with them. Your pages come alive for any user, even with the slowest Internet connection. Users will get quick responses because the interaction does not need to involve the server but can take place in their browser.
This interaction can change your pages into an application. Put together a few buttons, a text box and some code to produce a calculator. Or an editor. Or a game. Or the "killer" JavaScript application that everyone wants. Users will save your JavaScript enhanced pages to use your application again and again. We saved a Web page with a JavaScript calculator so we could have a calculator handy. We also have an HTML editor written in JavaScript saved on our hard drives.
JavaScript is a programming language that allows scripting of events, objects and actions to create Internet applications. This chapter will introduce you to JavaScript and let you learn the following:
In building Web pages, you present information to your audience. The design and layout should entice them to explore your site. Your hyperlinks provide several predefined, but different paths to see your information.
With JavaScript, your pages come alive! Your pages respond to the requests of your audience beyond a simple click here or there. Many more interactive elements are now available for exciting design and layout. Your users are no longer just readers. People will interact with your documents, not just read them. Your users can now interact with forms, change the look and feel of your Web documents and use multiple windows.
With JavaScript, forms are a consideration in nearly every page you design. Text fields and text areas can dynamically change in response to user responses. Your audience will look for buttons, selections, radio buttons, and checkboxes. Your pages will change at their touch. The following examples show you how JavaScript makes forms come alive:
Fig. 1.1 Calculator built in to a Web page with JavaScript.
Fig. 1.2 JavaScript time displays usually shows you the local time.
Fig. 1.3 Text boxes can feedback status of applications to users numerically, with ASCII graphics or verbally in text boxes.
Figure 1.4 Provide your users with instant feedback without waiting for a response from the server.
Fig. 1.5 Punchline: now you see the joke without the punchline revealed.
Fig. 1.6 Here's the punchline, hidden until you are ready to see it.
The source code in Listing 1.1 is easy to modify for you to tell your own jokes on the Web without giving away the punchline.
Listing 1.1 <HTML><HEAD><TITLE>javascript Punchline demo by Ray Daly</TITLE> <SCRIPT LANGUAGE="LiveScript"> <!-- hide this script from some browsers function Punchline () { document.write ("<BODY BGcolor=#00EE00><P> <I>To get to the other side.</P></I>") ; } // hidden ray.daly@mailcall.com 12/16/95--> </SCRIPT> </HEAD> <BODY> <H1>Punchline</H1> <H2>a javascript Punchline demo by Ray Daly</H2> <P>Why did the chicken cross the road?</P> <FORM> <P><INPUT TYPE="button" VALUE="Punchline" onClick=Punchline()> </P></FORM></BODY></HTML>
All of the elements inside the window of a browser are available in JavaScript. You can dynamically change some of these elements. Or you can examine the elements of one document and use that information to create a different document. Here are some examples of changing the look and feel of documents.
There are too many colors for a user to choose. Don't make them experiment, let them select some good combinations you have already tested.
Fig. 1.7 Sample of a menu where you can change the background color.
An example is HTML Analysis (see fig. 1.8). In the control panel at the bottom of the window, you specify a URL that is displayed in the left frame. The right panel is generated from the code activated by the REDO button. This code reads the HTML code of the left document and creates an entirely new docuement that lists all of the hyperlinks. This new document is displayed in the right frame.
Listing 1.2 shows the frames for HTML Analysis.
Listing 1.2 <HTML><HEAD><TITLE>HTML Analysis by Ray Daly</TITLE></HEAD> <FRAMESET ROWS="80,300,*"> <FRAME SRC="hanalys1.htm" NAME="control"> <FRAME SRC="" NAME="displayhere"> <FRAME SRC="" NAME="analysis"> <FRAME SRC="guide.htm" NAME="guide"> </FRAMESET></HTML>
Listing 1.3 shows the code for HTML Analysis.
Listing 1.3 <HTML><HEAD><TITLE>hanalys1.htm: part of hanalysi.htm</TITLE> <SCRIPT Lanuguage="JavaScript"> function doit() { for (i = 0; i <parent.displayhere.document.links.length; i++) { parent.analysis.document.write (parent.displayhere.document.links[i] [ccc] + "<BR>") } }</SCRIPT></HEAD> <BODY> <A HREF="http://www.cris.com/~raydaly/htmljive.html" TARGET="displayhere"> Get a page.</A> <FORM><INPUT TYPE="button" VALUE="Probe it" onClick="doit()"></FORM> </BODY></HTML>The HTML Analysis application is not stable on all platforms. Make sure the URL is completely loaded prior to doing the analysis.
Fig. 1.8 The URL specified in the top frame is displayed in second frame. The third frame shows only the links from that page. Such tools are a great way to make certain pages on your site meet your standards.You can reformat pages for dramatic results. Instead of showing the entire document in a large frame, bring the source document into an extremely small frame. Then display your reformatted document in the much larger frame. If the frame with your source is small enough, your users won't even know what the original looked like.
Netscape introduced frames and JavaScript with Navigator 2.0. You will probably also find yourself using another popular feature: opening multiple windows for browsing the Web. Add some JavaScript behind these new features and the browser becomes a kaleidoscope on the WWW. No longer are you limited to browsing one page at a time. Now you can view multiple documents and see a multifaceted view of the Internet world. The following list examines using multiple windows and frames:
Fig. 1.9 Alert boxes notify the user, but provide no choices.
Fig. 1.10 Confirm box notifies the user and allows them to cancel the action.
Fig. 1.11 Prompt box lets the user type a response to your code.
Fig. 1.12 Internet Tri-Eye is an example of a multi-window application and a control panel. Selections in one frame produce results in other frames.
Sun Microsystems and Netscape Communications introduced JavaScript. An additional 28 leading computer companies, including AOL, AT&T, Borland, Digital Equipment Corporation, Hewlett-Packard Corporation, and Oracle Corporation endorsed JavaScript. These companies support JavaScript because it is an open standard object language. Several companies will introduce products that incorporate JavaScript. This will allow even more interaction. The following products support JavaScript:
For more information on plug-ins, visit this site:
http://home.netscape.com/comprod/products/navigator/
version_2.0/plugins/index.html
Netscape Navigator 2.0 supports a new functionality-enhancing feature that provides inline support for a huge range of Live Objects. With Live Objects, developers can deliver rich multimedia content through Internet sites, allowing users to seamlessly view that content with plug-ins such as Adobe Acrobat, Apple Quick Time, and Macromedia Shockwave for Director in the client window- all without launching any external helper applications.
There is no definitive definition of a scripting language. Sometimes the term is used to make a distinction from a compiled languages like C or C++. The term scripting is also used because a language will react to, control or "script" a series of events. Even macro languages built into PC applications like spreadsheets, databases, word processors and multimedia applications are now often called scripting languages.
The purpose of most scripting languages is to extend the capability of an application. Just as the authors of this book cannot imagine every creative use you will make of JavaScript, software authors cannot imagine every possible use other their applications. To make their products more versatile, they add a scripting language. With JavaScript you have a scripting language to use your imagination on the Web.
Current uses of scripting languages may give you an insight of the potential for JavaScript. You probably know that macros are built into many PC applications. Apple's HyperCard contains a very powerful scripting feature. Perl is a scripting language used in many CGI scripts you use on the Web.
Traditionally, a macro feature was added to PC software to allow a simple series of commands to be executed with a single keystroke. With great fanfare publishers introduced this feature as a way to reduce repetitive tasks and save time. For example, a word processor's simple macro might change the entire style of a document.
Over time the macro feature of various applications became complex scripting languages. As scripts become longer and non-trivial, they extended the software beyond its normal purpose. New and creative combinations of commands made the software the basis for entirely new applications-for example, a set of word processing scripts for maintaining a small mailing list.
These scripting languages in software are so sophisticated that they are the subject of college courses. Many universities now require courses in spreadsheet scripting for accounting and business students. Art majors are learning scripting procedures for high-end graphics and multimedia packages. Legal courses include using scripts to create documents. And computer science majors have a variety of courses involving scripting languages.
A defining factor of this type of scripting language is that they only work with applications. Scripts in word processors add word processing features. Scripts in spreadsheets add spreadsheet features. These scripts do not go beyond the nature of the software, but they use the existing commands of the software. In our example, the mailing list script still works with words, the standard element of the word processor. This becomes a limitation on the usefulness of this script.
With the popularity of program suites like Microsoft Office, Lotus SmartSuite and Perfect Office, PC publishers have started making the same scripting language work with more than one application. Not only is the same language used in each application, the script language helps the applications work together. Microsoft expanded the role of Visual Basic to work with Microsoft Access and Excel. Lotus has developed LiveBasic for its product suite.
With the PC environement, the role of scripting languages is serious business. It's the subject of college courses and often used to build non-trivial applications. Just as the authors of this book cannot imagine every creative use you will make of JavaScript, software authors cannot imagine every possible use of their application. To make their products more versatile, they add a scripting language. With JavaScript you have a scripting language to use your imagination on the Web.
Historically, scripting has made several "killer applications." These are applications, which define a whole new category of software, significantly expand the market and provide a primary reason for people to use a computer. The first successful spreadsheet was VisiCalc, which disappeared with the success of Lotus 1-2-3. The latter had scripting. There were many different database applications on the market before Ashton-Tate's dBase, but this product was programmable with a scripting language.
Scripting gave these applications a great feature that people wanted. Perhaps more important were the actual scripts people created to extend the capabilities of these products. These existing scripts became an investment in these products that prevented users from switching to competitive products, even if they had more features.
Scripting gave these applications a competitive edge. First, it was a feature that could be used to sell the product. Second, people actually started to use the feature and create significant new capabilities for these products. Third, these scripts create a whole new market with magazine articles, books, third-party software publishers and training. Fourth, the continuing use of these scripts became an investment by the user in these products. Existing scripts often prevented users from switching to competive products. And finally, even when a competive product was introduced with new features, someone would introduce scripts that attempted to add these features into the existing products. Scripts allowed both the publisher and users to advance.
The most notable use of scripting on the Macintosh is Apple's HyperCard program. This application lets you build a group of cards and hyperlink them together. The cards could contain not only text but multimedia files. The stack of cards that you construct could respond to user input.
The scripting language is such a strong element of HyperCard that many people consider HyperCard itself to be a language. Many Mac owners were initially disappointed with HTML because it lacked many of the abilities of HyperCard. In many ways, JavaScript brings some of the HyperCard features to the Web.
If you have used the Web, you have used Perl. It is the language used for probably the majority of CGI scripts. These are routines that run on Internet servers and respond to requests from browsers when a user completes a form. There are guestbooks, message boards, voting pages, surveys and more that use Perl scripts.
Perl is an interpreted language. While you should be able to find a version of Perl for almost any computer platform, it was created for UNIX systems. It is now platform independent. The vast majority of Perl scripts will run without modification on any system. Take a script written on UNIX and it will run perfectly well on DOS.
CGI scripts are a type of script that responds to events. In this case, the event is a user submitting data from a HTML form. The attributes of a <FORM> include ACTION, which defines the script to process the data when it is submitted. For example:
<FORM ACTION="\cgi-bin\guestbook.pl">
will process the data from the form in a script called guestbook.pl. More than likely this routine would store the data in a file and return a HTML page to the browser as feedback. It would probably say something like "Thanks for your entry into our guestbook."
Perl is freely distributed on Internet, but please see its license for more detail. You should be able to find a version for your system using any of the Internet search services. Larry Wall is the sole maintainer.
Perl's strength as a language is in manipulating files and text to produce reports. This capability along with its associative arrays make it a natural fit for creating CGI scripts. In a few lines you can process data and return an HTML document in response to a HTML form.
If you are a Perl programmer, you can rather quickly learn JavaScript. Both have a similar control structure and both are interpreted languages. Unlike Perl, JavaScript is object-based but it is not nearly as complex. You might miss the text processing capabilities of Perl, but you find JavaScript a delightful new language to learn.
There are some cases where JavaScript is not the appropriate solution, but using Perl for a CGI script would fit the requirement. Generally, if you need to store information, you are going to have to do that on the server and Perl would be a good choice.
Like other scripting languages that extend the capabilities of the application with which they work, JavaScript extends the standard Web page beyond its normal use. You have already seen in this chapter numerous ways to make your Web site come alive. And given the flexibility of the language, the only limit is your imagination. We must now consider how JavaScript works within HTML pages.
JavaScript Pages Work Differently Than Standard HTML Pages
With the standard Web site, you get more information by clicking on a hypertext link and the server sends you another file. On a more interactive page, you complete a form, submit the results to the server and wait for a response. In either case you must wait on the server to send a new file. This information is almost always a new page, though it might be a multimedia file like an audio clip or an animation.
With JavaScript-enhanced pages, there is JavaScript code embedded in the HTML code. The JavaScript can instantly provide you information without waiting on the server or your Internet connection (see fig. 1.13). This information can come from user input, code 'hidden' with the document or other documents in frames or other windows.
This JavaScript-enhanced page makes this new information visible by updating the contents of a form or by generating an entirely new document. In a JavaScript calculator (refer to fig. 1.1), the form is updated when numbers are entered. In "Punchline" (refer to fig. 1.5), the user clicks on the button and a new document is created from the 'hidden' punchline of the joke.
Fig. 1.13 With standard HTML pages, a Web site serves each page to the browser. With JavaScript-enhanced pages, the source for a page can be the existing page.
JavaScript works with browsers by embedding code directly into an HTML page. Netscape added a new generic tag called <SCRIPT> to recognize scripting languages. To inform the browser that your code is JavaScript, you must add the attribute of LANGUAGE="JavaScript" to the <SCRIPT> tag. Much of your JavaScript coding is enclosed within these tags, as you can see in the following example:
<SCRIPT LANGUAGE="JavaScript"> a = "Hello!" //...set a variable called 'a' to a value of "Hello!" </SCRIPT>
Like most any other computer language, JavaScript allows you to place comments within your code. Single-line and multiple-line comments are possible. A multiple line starts with the following two characters: /*
It ends with the two characters: */
Consider the following example:
/* This is the start of multiple lines of comments.
This is the end */
To make a comment at the end of a line or on a single line, just use the characters // and everything after that mark until the end of the line will be considered a comment.
Between <SCRIPT> tags you can write two types of code: direct statements and functions. Direct statements are executed by the browser as they are loaded. For example, objects are initialized in direct statements. Functions are blocks of code that are executed only by other code or events.
See Chapter 3, "Events and JavaScript" for more information about code and events.For example, mouse-click events usually trigger functions. Most of your programs will use both direct statements and functions.
Many existing HTML tags now have additional attributes to support JavaScript. For example, all elements of a form can now be identified with the NAME element. You should be familiar with the NAME attribute because it has long been used in creating anchors. Using NAME to identify objects in your documents will generally simplify your coding and debugging.
The final addition to HTML is recognizing events like mouse clicks, changes in text boxes, and the loading or unloading of pages. This is how the document recognizes the user interaction. These events are used to trigger JavaScript actions. The code can be quite straightforward, as in the following:
<FORM> <P>Click inside the box and then out to see change. <INPUT TYPE="text" NAME="sample" onChange = "sample.value = a" > <!-- ...after any change in this text box, but the value of a in the box --> </FORM>
The JavaScript code that is triggered by an event can be simple or complex. With simple actions, the entire code can be placed in the event element. This is shown in the previous example with sample.value = a. Throughout this book you will see a more typical example of where a function is called by the event.
Like any language, JavaScript performs operations. These operations, or methods, manipulate information about objects. Other than string, math, and date objects, JavaScript is limited to operating on browser objects. This allows you to create new documents and modify your existing forms.
JavaScript works with browser objects, which makes the language easier to learn. Most of the code manipulates HTML elements that you already know. For example, it will read properties of a LINK or write information into a TEXTAREA. Use elements you already know about to make pages come alive.
But this is a limitation. There are not any new operations that give you multimedia capability like sound or graphics. To add these types of features, you need to extend the capability of the browser with plugins or Java applets. These programs may or may not recognize JavaScript.
Plugins are written by software publishers to add capabilities to the Netscape Navigator. These publishers are not required to make these plugins work with JavaScript. So you must look at the specifications of a plugin to see if it supports JavaScript.
This feature is not supported in version 2.0, but is planned for version 2.1 of Netscape Navigator.
Java and JavaScript are alike in more than just name. However, there are significant differences between these two languages. As you learn to understand the differences, you will also understand how they can work together. Each has its place and neither does it all. Table 1.1 provides a quick overview of the differences.
See Chapter 11, "A Java Tutorial" for more information about Java.Table 1.1 Comparing JavaScript and Java | |
---|---|
Interpreted by client | Compiled by the author, run on client |
Code integrated in HTML documents | Applets distinct from HTML document |
Loose typing of data types | Strong typing of data types |
Dynamic binding | Static binding |
Script limited to browser functions | Stand-alone applications |
Works with HTML elements | Goes beyond HTML (for example, multimedia) |
Access browser objects and functionality | No access to browser objects or functionality |
Both JavaScript and Java are languages for building Internet applications. These applications require browsers. The browsers run these applications by reading code embedded in a HTML page. In other words, they both work in the same environment.
Sun and Netscape have mounted a high profile campaign to insure the security of these products. Neither product writes to the user's hard drive. Sensitive information about the user is also unavailable to these languages. So both products are limited by security and privacy concerns of their environment.
Because the two products have a similar name and work in the same environment, many people do not realize the distinction between JavaScript and Java.
In addition, it appears that more Internet browsers will support Java than JavaScript, though this is not certain. They display information differently in a browser window. Java applications can stand alone. One is compiled, the other is interpreted. The development tools are different, and they have a surprisingly different audience.
To display information on a Web page, Java is limited to painting its text and graphics within a defined area. Just like images on a page are drawn within a defined area of the page, so to with Java programs. Within these areas the Java applets can create animations, paint and use various fonts. However, an applet can not effect anything outside its area.
JavaScript gives you access to the entire Web page. You can modify properties of the page or any element of the page. You can create new documents or update parts of a form. Unlike Java, JavaScript lets you change the appearance of any part of your Web documents, not just a limited area.
The hype on Java is that is flexible enough to do anything. Currently, it can NOT effect anything in a Web page outside of the area to which it is assigned. If you want your HTML document to interact with Java, forget it. The only way for Java to control everything on the screen is to write a program from scratch and recreate the entire screen. You basically have to rewrite some browser functions.
To access browser objects, Java is expected to work more closely with JavaScript in future editions. This should enhance the capabilities of both languages.
Directly related to this is Sun's work on a new version of Hot Java, its Web browser. Apparently the new version's primary goal is to make available general purpose browser routines for Java programmers. It is not clear at this time how this will play out, but the development of Hot Java is worth watching.
Java is a general purpose language that can create stand-alone applications. Unlike the Java applets that run in Web pages, these applications may not even connect to the Internet but perform business functions like accounting. This is an important aspect of Java that has many people excited.
JavaScript, like most other scripting languages, works only with an application. Currently it works with Netscape's Navigator browser and the LiveWire server environment. In the near future it will also work with plugins. But JavaScript applications will not function independently.
Hot Java (not to be confused with Java or JavaScript) is Sun's own Web browser written in Java. It showed that Java applications could stand-alone. This browser's purpose was to demonstrate the early applets written with the alpha version of Java. With the official release of Java version 1, the original Hot Java is no longer a viable browser. It will not run applets written in Java version 1. A new version of Hot Java is apparently in the works which will support both Java 1.0 applets and JavaScript.
With Java you write your code, compile it, and then run it. The person using your Java applet from a Web page cannot look at the source code. For many programmers, there is a sense of security here that you are not giving away your code.
JavaScript is interpreted. The code you write in JavaScript is the code that the browser executes. There is not intermediate step of creating executable code from the source code. People can look at the source code of the HTML page and read your JavaScript code and your comments.
The first generation of development tools for these languages are just being introduced. Since JavaScript and Java are very new languages, this is not surprising. However, looking at the nature of the products, some general distinctions between the development tools can be made.
Java is very much like C++ language. It is object-oriented, uses many same statements, uses libraries, and is compiled. Several companies that have strong C++ programming environments are developing similar environments for Java. This will allow the development of large scale Java applications, but you will have to learn these programming environments.
See Chapter 18, "Tools for JavaScript Development" for more information.JavaScript is tied to the HTML page. The code is embedded in it and it operates on HTML elements. Since the code is interpreted by a browser, it is anticipated that HTML editors will add features for creating JavaScript code.
Java requires a preemptive multitasking operating system. So anyone operating on the Unix platform, OS/2, Windows NT and 95 and Macintosh will be able to run Java applications and applets. This is a substantial part of the Internet audience.
JavaScript works in any version of Netscape Navigator on any platform it supports. Obviously this is also a substantial part of the Internet audience.
There are some big differences between these audiences. The biggest difference is that millions of people running Windows 3.1 can run Netscape Navigator and thus enjoy JavaScript enhanced pages. These same people can not run Java applets or applications.
However, it appears that more Internet browsers will support Java than JavaScript, though this is not certain. So while you might have a computer that runs JavaScript, your browser might not support it.
So in the near future it appears that JavaScript has a wider audience due to the Windows 3.1 users. However, as these people upgrade and as new Java-compatible browsers become available, it seems Java will develop a larger audience.
Because JavaScript is an interpreted language, there is a huge audience of potential JavaScript authors. All it takes to write a JavaScript program is a JavaScript compatible browser like Netscape 2.0 and a text editor. Most HTML editors can also be used to write JavaScript code. So, millions of people now have all the tools they need to create JavaScript applications. In a matter of a few days Netscape was able to distribute probably millions of JavaScript interpreters. It took Microsoft years to distribute nearly as many copies of Microsoft Basic into computers.
Learning JavaScript is almost easy. By typing in just a few lines, you can be running a JavaScript application. As you read through this book you will quickly be incorporating many scripts into your pages. But just as nearly anyone can plant a seed, it does take some patience and skill to create a garden.
One of the more important aspects of Sun and Netscape's cooperation is the commitment to make the languages work together. They share a similar syntax and control structure that make it easier to write code for either language. But more importantly, a JavaScript page will be able to communicate with the Java applet referenced by the page.
Another aspect of this sharing takes place not in the browser, but in the server. Netscape's new LiveWire graphic environment will support both Java and JavaScript so the scripting language that works on the browser will also work on the server. Just as interactive scripts currently run as CGI scripts, JavaScript can handle such interaction on these new servers that support LiveWire.
JavaScript will be incorporated into more Internet tools. While Netscape introduced JavaScript with Navigator 2.0, Sun and Netscape are making it an open, cross-platform scripting language. This means that any publisher can use it as his scripting language. This is the primary reason why 28 other companies endorsed JavaScript upon its release.
Several of these companies are expected to either incorporate JavaScript into their products or provide an interface to JavaScript. The most visible products will be the plugins to Netscape Navigator, as discussed previously. Also, the Professional version of the LiveWire environment uses JavaScript to access high-end databases. It will be interesting to see how this market develops.
All of this holds great potential for creating an exciting Web experience for your viewers. You will be able to use the same language to enhance your Web page, customize your server, create stunning effects with your plug-ins, and communicate with specialized Java applets. JavaScript can make your Web page come alive; it can make your site an unforgettable experience that your users will want at the top of their bookmarks.
|