Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Java Unleashed

Java Unleashed-ch41.htm Previous Page toc Index Next Page

Chapter 41

Java script

One of the most intriguing and exciting aspects of the World Wide Web is its capability to offer interactive content to many people. Thousands upon thousands of pages are linked together across the globe, each accessible with a single mouse click. The Web is the largest collection of information available to a single person since the beginning of time. As incredible as these notions may be, the users of the Web demand more. As technology on the Web improves, users want more interaction, more sophistication, more visually appealing content, and above all, these users want to be able to create this content themselves.

Java has turned the promise of interactivity into reality. For the first time, programmers can create small software programs, or applets, that can be distributed and executed easily on the World Wide Web. Netscape Communications ( has single-handedly helped to thrust this new technology into the mainstream by incorporating Java into its popular Navigator software. For the first time, Web sites can finally interact with their users. Sophisticated applications like paint programs, spreadsheets, games, and complex math engines can now run in the browser window, among HTML pages, without the need of specialized hardware or software, other than a Java-enabled browser such as Netscape’s Navigator.

Two distinct solutions to interactive content creation have formed on the Web: the simple-to- use Hypertext Markup Language (HTML), and the sophisticated and powerful Java programming language. With these two tools, users can create the visually compelling content and have it merge seamlessly with the interactive applications that Java offers. Nevertheless, what seems to be missing is a system for bringing these two technologies closer together.

Welcome to JavaScript

Netscape Communications saw the need for a bridge between these two technologies. They began working on a new scripting language that could have a place between HTML and Java, yet be powerful enough to link the two technologies together. When Netscape’s new scripting language was introduced, it was known as LiveScript. It was immediately incorporated into their Navigator product in an effort to quickly have it adopted by the Internet community. Soon thereafter, seeing the potential of a joint effort, Netscape and Sun teamed to help LiveScript become more mainstream and to establish it as the standard in the Internet community for Web-based scripting. Because LiveScript syntax was so similar to Java’s syntax, Sun and Netscape decided to rename their new product to make it more recognizable. It would now be called JavaScript.

JavaScript was created as an easy-to-use, open, cross-platform scripting language that could link together objects and resources from both HTML and Java. While Java applets are primarily developed by programmers, JavaScript was intended to be used by HTML page authors to dynamically control the interaction and behavior of their pages. JavaScript is unique in that it has been designed to be complementary to and integrated with both HTML and Java. One of the most important benefits JavaScript offers is its capability to reduce network traffic by keeping simple tasks local. In other words, instead of the server performing tasks and returning the results to the browser, the browser can handle some of the tasks locally, thus giving the user quicker response times.

JavaScript has been endorsed by over 25 industry-leading companies, including America Online, Inc., Apple Computer, Inc., Architext Software, Attachmate Corporation, AT&T, Borland International, Intuit, Inc., and Silicon Graphics, Inc. These companies plan to introduce products adopting the JavaScript language which will help to establish it in the Web community. JavaScript has also been submitted to the appropriate standards bodies for industry review and commenting.

These four chapters on JavaScript provide an introduction into JavaScript and do not cover the entire scope of JavaScript. They are here as a starting point into your exploration of this new and unique scripting language. Because JavaScript is still an evolving language, some of its features and commands may change in the future. Every effort has been made to make the information contained here as timely as possible.

Learning JavaScript

JavaScript is based on the powerful Java language in its syntax and usage, yet is interpreted, not compiled. What this means is that the JavaScript application code is downloaded as text into the browser along with the HTML text. The code is executed within the browser, enabling you to develop simple applications that can interact with and assist your users.

With JavaScript, you can respond to events from the user such as mouse clicks, mouse movement over a link, and form input. You can build dynamic pages that change according to your user’s requests, or even play sounds or run applets when a user enters or leaves your page. This type of capability at the client level allows for tremendous interactivity with the users of your Web pages.

The JavaScript language resembles Java, but is simpler and easier to learn. A JavaScript application may be as short as one line or take several pages. The complexity depends on the extent in which your script interacts with the page it is in. One of the first uses of JavaScript for most authors is in form validation. Form validation is the ability for an HTML form to check the input from a user before it is submitted, which greatly improves performance on your server as well as decreases user frustration. Listing 41.1 shows a simple example of form validation.



<FORM NAME=”demoform” onSubmit=”if(! 

     { alert(‘You left the name field blank’); return false; }”>

<INPUT NAME=”name””> 

<INPUT TYPE=”submit”>




The short HTML document in Listing 41.1 is a testament to the power and simplicity of JavaScript. The document displays a form that cannot be submitted until something is entered into the name field. If the field is left blank, a window will open stating You left the name field blank. Once information has been entered, the form may be submitted normally.

Learning JavaScript isn’t difficult, but requires considerably more effort than HTML. Despite its simplicity, JavaScript is based on a programming language, making it much more sophisticated than HTML. It requires a time investment and a lot of experimentation. Fortunately, JavaScript applications are easy to develop and easy to test; this ultimately leads to a speedier grasp of the JavaScript language. As an added benefit, by learning JavaScript, you will have begun your journey into Java programming. JavaScript is based on Java, so many of the commands and constructs are similar, if not the same. The next section discusses the similarities and differences in these two languages.

JavaScript and Java

JavaScript was designed to help the nonprogrammer in creating interactive applications for the Web and to facilitate the integration of Java and HTML. Despite these two seemingly different roles, JavaScript and Java are based on the same basic principles. They are both programming languages with similar commands and syntax, they are both object-oriented, and they are both open- and cross-platform. Following is a comparison of the two languages.

Comparing and Contrasting

JavaScript is very similar to Java in its syntax, but many of the similarities stop there. JavaScript is an interpreted language, meaning that JavaScript code runs directly within the browser and requires no compilation, whereas Java requires compilation prior to execution. In addition, JavaScript supports a smaller set of data types compared to Java, and JavaScript methods do not require special declarations like Java methods.

In contrast to Java, JavaScript contains many built-in objects that require minimal effort for their creation. JavaScript has no classes or class inheritance like Java, but rather relies on its built-in set of objects to be extended in order to suit the needs of the programmer. Because JavaScript is interpreted and not compiled, all object references are checked at runtime, whereas Java requires that all references exist at compile time. Also, a variable’s datatype need not be declared in JavaScript like is it required in Java.

Another major difference between Java and JavaScript is in JavaScript’s tight integration with HTML. Java applets may be called from within an HTML document by use of the <APPLET> tag, but the actual compiled code resides in a separate file. JavaScript enables you to embed the source code directly into the HTML code, resulting in a single file for both HTML code and JavaScript source code.

Security Considerations

Like Java, JavaScript has been designed from the ground up to be a secure language. Neither Java nor JavaScript allows the use of pointers, which is commonly the cause of security violations. Because JavaScript is an interpreted language, there are no compile-time memory allocation concerns, which are another potential cause of security violations. In addition, in order to minimize the effectiveness of malicious programs, disk writes are not allowed in either Java or JavaScript.

In the Java language, the application code is compiled into byte-code on the server. This byte-code file, generally with a .class extension, is the actual program that is received and run by the Java-enabled browser. This .class file, because it is compiled, does not contain the original source code of the application, thus making your source code unavailable to the user. In contrast, because JavaScript code is embedded in the HTML as plain text, the user may view the source to the HTML file, and in turn, view the source code to your JavaScript application. Currently, it is not possible to protect the source code other than by placing a copyright notice in the source of your JavaScript application.

Integrating JavaScript and Java

One of the much-touted features of JavaScript is its capability to directly interact with Java applications. In the Java code, useful properties can be exposed to allow a JavaScript application to get or set these properties and alter the state or performance of the Java application. This same paradigm also applies to Netscape Navigator plug-ins, meaning a JavaScript could query and alter the performance of a plug-in, as well.

In the first released version of JavaScript, which is included in Netscape Navigator 2.0, this tightly coupled interaction with Java is not yet implemented. The next major release of JavaScript, slated to appear in Netscape Navigator 2.1, will enable you to call Java methods from JavaScript directly and get and set public Java fields. This integration will allow for more dynamic content and interactivity within pages that contain both Java applets and JavaScript code.

Many future applications on the World Wide Web will feature complex and sophisticated interfaces and interactivity. For example, suppose you wanted to create an HTML page that contained the logo of your company on top, a visually integrated three-dimensional image of an automobile in the center, descriptive text about the automobile below, and form controls for rotating the automobile in any direction you desired. This HTML page sounds exciting, but you would face very complex programming issues if you were trying to develop such an application entirely in Java.

By allowing Java to perform the tasks it is best at, perhaps rotating and rendering the 3D car image, JavaScript can handle the interaction between the form controls and the Java application, sending the Java applet messages about what the user has chosen as rotation angles. Finally, HTML can be used to establish the framework, displaying the title logo, and building the actual form elements. By integrating all these technologies together, HTML, JavaScript, and Java, the development and implementation of highly interactive Web pages can become easier and faster to complete.

Halfway to Java with JavaScript

One of the most promising aspects of learning JavaScript is that it will enable you to begin understanding the basic structures of object-oriented programming. Object-oriented programming is rapidly becoming the standard in programming languages of the future. Today, C++ has set the standard for object-oriented programming, and is used widely across the globe. It is no wonder that both JavaScript and Java resemble the syntax of C and C++. Many of the constructs of those languages have been passed on to JavaScript and Java, making it easier for programmers to transition to these new languages.

If you have never programmed before, JavaScript will enable you to begin the process of understanding how these languages work. Because of the similarities between JavaScript and Java, once you have learned and grasped the basic concepts of JavaScript, you will already be well on your way to mastering Java. With the combination of these two languages at your disposal, compelling and interactive content is yours for the making. Spending the time reading these chapters carefully, completing all of the examples, and then, of course, experimenting with your own applications will soon make you a master at these powerful tools.

JavaScript Requirements

JavaScript, unlike Java, requires few resources to use and program. One of the exciting aspects of JavaScript is that nearly anyone can use it and develop their own applications right away. Most users already have all of the tools they need on their computers right now. Because JavaScript is an interpreted language and not compiled, the usual requirements associated with compiled languages, compilers, linkers, debuggers, and so on, are not needed. As a result, JavaScript imposes a very minimal set of requirements in order to begin developing with it immediately.

Required Software and Hardware

Because JavaScript was developed by Netscape, Netscape’s Navigator program is the first program to support JavaScript directly. Every version of the Netscape Navigator across all platforms supports JavaScript. These platforms includes Macintosh, Windows, Solaris, SunOS, HP-UX, IRIX, AIX, Digital UNIX, Linux, NetBSD, and FreeBSD. In turn, the hardware requirements for running JavaScript are the same as the requirements for running the Netscape Navigator. In other words, if you are currently using the Netscape Navigator for Web browsing, you already have all of the hardware and software required to run JavaScript applications.

Developing for JavaScript is as simple as running JavaScript applications. Because JavaScript is interpreted, and therefore completely plain-text-based, any editor can be used to create JavaScript-enabled Web pages. Whichever editor you use now, whether it be NotePad for Windows, vi or emacs on UNIX, SimpleText on the Mac, or any of the host of HTML editors, they all have the capability to produce JavaScript code. Because JavaScript does not need to be compiled, as soon as you save your JavaScript code, you can immediately test it, right in your browser.

With over 25 companies already dedicated to providing tools and applications based on JavaScript, including Netscape, there will soon be a large collection of tools available to more specifically focus on the development process of JavaScript applications. Netscape’s Navigator Gold product contains a full What You See Is What You Get (WYSIWYG) HTML editor built into the browser and allows you to enter JavaScript code directly. By being able to instantly switch back and forth between JavaScript source and the final HTML page, Navigator Gold promises to make it even easier for anyone to create compelling, JavaScript-based Web pages.

Authoring with JavaScript

Creating a JavaScript program is a relatively simple process. Using any text editor, you may begin typing in JavaScript statements to expand the role of your current HTML pages, create entirely new pages using only JavaScript, or mix both HTML and JavaScript. This section will cover some of the issues and syntax in creating a JavaScript application, as well as information on how to embed your JavaScript code into your HTML documents.

Creating Your Script

In order for your browser to recognize that there is JavaScript code in your file, two special tags have been introduced.


Between these two tags, JavaScript code may be inserted and the browser will recognize the JavaScript code while loading your page. The <SCRIPT> tag also has attributes that can be specified.


The LANGUAGE attribute specifies the language to use for the script. Currently, only “LiveScript” and “JavaScript” are used. The “LiveScript” name is a legacy attribute from an older version of JavaScript.

<SCRIPT SRC=”http://myjavascript.js”>...</SCRIPT>

The SRC attribute is optional and, if given, specifies an URL that loads the text of a script. A script from a SRC is evaluated before in-page scripts. Also, any SRC URL should use the .js suffix.

<SCRIPT LANGUAGE=”language” SRC=url>...</SCRIPT>

You may also specify both a LANGUAGE and a SRC attribute together.

The JavaScript code is evaluated after the entire page loads, and if you are using any JavaScript functions, they will be stored by the browser, but not executed without a specific call to that function.

In order to create a script, simply use your favorite text or HTML editor and begin typing in JavaScript code. Listing 41.2 illustrates a simple JavaScript program.




document.write(“<H1>JavaScript is Fun!</H1>”)




<h2>This is normal HTML.</h2>



When the script is run, it produces what is shown in Figure 41.1. The JavaScript is Fun! message is produced by the JavaScript code, while the This is normal HTML. is HTML text. Notice how the JavaScript statement document.write() is inserted between the HTML tags <SCRIPT>...</SCRIPT>. This tells the browser that JavaScript code is located between the tags and not standard HTML.

Figure FIGURE 40.1.

Javascript application displaying a message in the Netscape Navigator along with HTML text.

Embedding the Script in Your HTML

Now that you know how to create a simple JavaScript program, there are some issues to address concerning embedding your JavaScript into HTML documents. As we have already seen, the <SCRIPT>...</SCRIPT> tags are used to denote JavaScript code from normal HTML code. Browsers that do not recognize a particular tag generally ignore them, so the <SCRIPT> and </SCRIPT> tags would not show up on a non-JavaScript-enabled browser. Unfortunately, the code within the SCRIPT tags would not be ignored but would display as unwanted output on your web page. Netscape Navigator solves this problem by enabling you to use HTML comment tags to comment out the portion of JavaScript code that other browsers would treat as plain text. In other words, when a browser that cannot support JavaScript comes across the comment tags, it will ignore everything in between them, where Netscape Navigator will not. Listing 41.3 uses the same code from Listing 41.2, but now comments out the portion that non-JavaScript browsers could not understand.




<!-- Begin to hide script content from old browsers.

document.write(“<H1>JavaScript is Really Fun!</H1>”)

// End the hiding here. -->




<H2>This is normal HTML.</H2>



Notice the <!-- and --> tags. These are HTML tags denoting a comment within the document. Netscape Navigator knows to look within these tags for JavaScript code. You may have also noticed two slashes // before the End the hiding here statement. Because we were within the SCRIPT tags, Netscape Navigator would try to execute the line as a statement. The two forward slashes is a JavaScript statement for denoting a comment line. The combination of the HTML comment tags and JavaScript comment tags help to ensure compatibility of your documents across many different types of browsers that fully suppport HTML commenting. Chapters 41 and 42 contain more in-depth examples of creating JavaScript applications, including JavaScript applications with functions.

Running Your Script

Running your JavaScript code is as easy as viewing an HTML page. Once your code is complete, simply load the page into your browser for instant results. This ability to instantly run and check your JavaScript code is another powerful feature of JavaScript. In the development and testing process of a JavaScript application, your computer does not need to be connected to a network. You can edit, test, and execute your JavaScript applications without ever being online. This can be a real advantage when hourly connect charges are a concern. Also, because you are testing your applications locally, load times will be extremely fast, and because JavaScript executes the code immediately, your entire development process will be extremely efficient and rewarding.

Future Enhancements to JavaScript

JavaScript is still in its infancy and as of this writing, the final version of JavaScript has not yet been released. Some of the features of JavaScript may change in the future, and new features will surely be added. Nevertheless, the core technology of JavaScript will not change any time soon. When new versions of JavaScript arrive, minor changes may have to be made to older code, but most code should work unmodified. It is also important to note that JavaScript has already been submitted to appropriate standards committees.

Future versions of JavaScript promises total integration with Java applets as well as integration with Netscape Navigator plug-ins. Other new software systems that use JavaScript extensively are also available. For example, Netscape’s LiveWire system uses server-based JavaScript code to integrate together database engines and HTML, as well a host of other capabilities. One of the best ways to stay abreast of the latest changes in this fast-moving industry is to stay tuned to the various resources available to you on the Internet.

JavaScript Resources

As JavaScript expands in popularity and its usage becomes more widespread, more and more resources will become available. Currently, there are many Web sites that contain example JavaScript applications as well as tutorials, documentation, and collections of other resources on JavaScript on the Web. Following are a few web sites of interest; these sites will also point you to other sites containing even more information on Java and JavaScript:

There are also books available on JavaScript that go into more detail than these chapters. They cover expanded issues of JavaScript, as well as providing more examples on how to best utilize JavaScript for your requirements. Teach Yourself JavaScript in 21 Days by Sams Publishing is an example of one of these books.


JavaScript is a powerful, interpreted scripting language that is built-in to the Netscape Navigator software. JavaScript is full-featured and allows for the creation of dynamic pages, interactive content, forms input checking, and much more.

JavaScript’s syntax is based on Java’s syntax, but otherwise remains as a different language with a different role. JavaScript excels in its ability to add client-side processing of forms, create HTML content on-the-fly, and tightly integrate HTML with Java.

JavaScript requires only a text editor for the creation of applications, and because Netscape’s Navigator has a built-in JavaScript interpreter, JavaScript applications may be run immediately after they have been typed in simply by loading them into the browser window.

JavaScript enables you to embed your JavaScript code directly into an HTML document with the use of the <SCRIPT>…</SCRIPT> tags. By hiding the code from other browsers using HTML comment tags and JavaScript comment statements, you can try to ensure that your JavaScript page stays compatible with most browsers that do not support JavaScript.

The next chapter delves into the JavaScript language itself, its syntax, and how you can use the language to create your own JavaScript-enabled Web pages.

Previous Page toc Index Next Page