Remember the thrill of visiting 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.
JavaScript is a programming language that allows scripting of events, objects, and actions to create Internet applications.
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 textareas 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:
The source code in listing 1.1 is easy to modify to tell your own jokes on the Web without giving away the punchline.
Listing 1.1 javapnch.htm Code for JavaScript
Punchline
<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. The following are some examples of changing the look and feel of documents:
TIP |
There are too many colors for a user to choose. Don't make them experiment; let them select from some good combinations you have already tested. |
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 document 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 hanalysi.htm Frames for HTML
Analysis
<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 hanalys1.htm Code for HTML
Analysis
<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] + "<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>
CAUTION |
The HTML Analysis application is not stable on all platforms. Make sure the URL is completely loaded prior to doing the analysis. |
TIP |
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. Microsoft Internet Explorer 3.0 also supports JavaScript, frames, and multiple windows. 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:
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. Microsoft supports JavaScript in Internet Explorer 3.0. 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/.
Microsoft is actively promoting its scripting language VBScript. The primary function of this language is to interact with and create external applications. Because this language is a subset of Microsoft's Visual Basic and works with ActiveX controls, it is expected to have a substantial impact.
There is no definitive definition of a scripting language. Sometimes the term is used to make a distinction from compiled languages. However, some languages like C or C++ can be used for scripting as well as full applications. 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 capabilities of 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 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 in to 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 became longer and nontrivial, 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 SmartSuites, and Perfect Office, PC publishers have started making the same scripting language work with more than one application. (Some would say that, at this point, macro languages become scripting languages.) 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 environment, the role of scripting languages is serious
business. It's the subject of college courses and often used to
build nontrivial applications.
NOTE |
Historically, scripting has made several "killer applications." These are applications, that 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 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 created 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 competitive products. And finally, even when a competitive 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 can contain not only text but multimedia files. The stack of cards that you construct can 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 capabilities 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.
A CGI script is a type of script that responds to events. In this case, the event is a user submitting data from an 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 an 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 the 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 an 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 will 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.
With the standard Web site, you get more information by clicking a hypertext link and having the server send 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 the Punchline script (refer to fig. 1.5), the user clicks the button and a new document is created from the hidden punchline of the joke.
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>
NOTE |
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 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 */ |
NOTE |
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.
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 more typical examples of where functions are called by events.
Like any language, JavaScript manipulates data. Being an object-based language, there are methods and functions that act on the data in the objects. Other than string, math, and date objects, JavaScript is limited to operating on browser objects and other objects exposed to the browser. These other objects can include plug-ins, Java applets, and ActiveX. This allows you to create new documents, modify your existing forms, and build applications.
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 plug-ins, Java applets, or other external applications.
These programs may or may not make their objects available to
JavaScript.
CAUTION |
Plug ins are written by software publishers to add capabilities to the Netscape Navigator. These publishers are not required to make these plug ins work with JavaScript. So you must look at the specifications of a plug in 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. |
JavaScript and Java 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.
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 functionality objects or |
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 ensure 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.
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.
Java Displays Are Limited to a Graphic Area 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 it is with Java programs. Within these areas the Java applets can create animations, paint, and use various fonts. However, an applet cannot affect 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.
NOTE |
The hype on Java is that it is flexible enough to do anything. Currently, it cannot affect 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 re-create 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 HotJava, 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 HotJava is worth watching. |
Java Applications Can Stand Alone 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 excited many people.
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 plug-ins. But JavaScript applications will not
function independently.
CAUTION |
HotJava (not to be confused with Java or JavaScript) is Sun's own Web browser written in Java. It has shown that Java applications can 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 HotJava is no longer a viable browser. It will not run applets written in Java version 1. A new version of HotJava, which will support both Java 1.0 applets and JavaScript, is apparently in the works . |
Java is a Compiled Language 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 no 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.
JavaScript and Java Development Tools 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 the C++ language. It is object oriented, uses many of the 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.
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.
JavaScript and Java have Different Audiences Java requires a multi-tasking, multi-threaded environment. So anyone operating on the Unix platform, OS/2, Windows NT and 95, or 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 2.0 and above, as well as any version of Microsoft Internet Explorer and above. Given the many platforms these browsers support, 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 cannot run Java applets or applications.
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. But those that do not support JavaScript should be a minority with Microsoft and Netscape supporting both languages.
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 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 important, 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. Perhaps 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 plug-ins 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.