Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Introduction

Introduction

This seventh edition of the JavaScript Bible represents knowledge and experience accumulated over fifteen years of daily work in JavaScript and a constant monitoring of newsgroups for questions, problems, and challenges facing scripters at all levels. Our goal is to help you avoid the same frustration and head-scratching we and others have experienced through multiple generations of scriptable browsers.

While the earliest editions of this book focused on the then-predominant Netscape Navigator browser, the browser market share landscape has changed through the years. For many years, Microsoft took a strong lead with its Internet Explorer, but more recently, other browsers that support industry standards are finding homes on users' computers. The situation still leaves an age-old dilemma for content developers: designing scripted content that functions equally well in both standards-compliant and proprietary environments. The job of a book claiming to be the "bible" is not only to present both the standard and proprietary details when they diverge, but also to show you how to write scripts that blend the two so that they work on the wide array of browsers visiting your sites or web applications. Empowering you to design and write good scripts is our passion, regardless of browser. It's true that our bias is toward industry standards, but not to the exclusion of proprietary features that may be necessary to get your content and scripting ideas flowing equally well on today's and tomorrow's browsers.

Organization and Features of This Edition

Like the previous three editions of the JavaScript Bible, this seventh edition contains far more information than can be printed and bound into a single volume. The complete contents can be found in the electronic version of this book (in PDF form) on the CD-ROM that accompanies the book. This edition is structured in such a way as to supply the most commonly needed information in its entirety in the printed portion of the book. Content that you use to learn the fundamentals of JavaScript and reference frequently are at your fingertips in the printed version, while chapters with more advanced content are in the searchable electronic version on the CD-ROM. Here are some details about the book's structure.

Part I: Getting Started with JavaScript

Part I of the book begins with a chapter that shows how JavaScript compares with Java and discusses its role within the rest of the World Wide Web. The web browser and scripting world have undergone significant changes since JavaScript first arrived on the scene. That's why Chapter 2 is devoted to addressing challenges facing scripters who must develop applications for both single- and cross-platform browser audiences amid rapidly changing standards efforts. Chapter 3 introduces some tools you can use to compose your pages and scripts, while Chapter 4 delves into the nitty-gritty of how to use JavaScript to run in a wide variety of browsers.

Part II: JavaScript Tutorial

All of Part II is handed over to a tutorial for newcomers to JavaScript. Ten lessons provide you with a gradual path through browser internals, basic programming skills, and genuine browser scripting, with an emphasis on industry standards as supported by most of the scriptable browsers in use today. Exercises follow at the end of each lesson to help reinforce what you just learned and challenge you to use your new knowledge (you'll find answers to the exercises in Appendix D, on the CD-ROM). The goal of the tutorial is to equip you with sufficient experience to start scripting simple pages right away while making it easier for you to understand the in-depth discussions and examples in the rest of the book.

Part III: JavaScript Core Language Reference

Reference information for the core JavaScript language fills Part III. In all reference chapters, a compatibility chart indicates the browser version that supports each object and object feature. Guide words near the tops of pages help you find a particular term quickly.

Part IV: Document Objects Reference

Part IV, the largest section of the book, provides in-depth coverage of the document object models as implemented in today's browsers, including the object used for modern Ajax applications. As with the core JavaScript reference chapters of Part III, these DOM chapters display browser compatibility charts for every object and object feature. One chapter in particular, Chapter 26, contains reference material that is shared by most of the remaining chapters of Part IV. To help you refer back to Chapter 26 from other chapters, a shaded tab along the outside edge of the page shows you at a glance where the chapter is located. Additional navigation aids include guide words near the tops of most pages to indicate which object and object feature is covered on the page. Note that the Objects Reference begun in Part IV of the book continues in Part VI on the CD, with an additional 13 chapters of reference material.

Part V: Appendixes

Appendix A offers a JavaScript and Browser Objects Quick Reference. Appendix B provides information about using the CD-ROM that comes with this book, which includes numerous bonus chapters and examples.

Part VI: Document Objects Reference (continued)

Beginning the portion of the book that resides only the accompanying CD, Part VI continues the document objects reference discussions that begin in Part IV by providing an additional 13 chapters of reference material.

Part VII: More JavaScript Programming

Chapters 4651 discuss advanced JavaScript programming techniques, including data-entry validation, debugging, and security issues.

Part VIII: Applications

The final ten chapters of the book, available only on the CD-ROM, feature sample applications that cover the gamut from calendars to puzzles.

Part IX: Appendixes (continued)

The final three appendixes provide helpful reference information. These resources include a list of JavaScript reserved words in Appendix C, answers to Part II's tutorial exercises in Appendix D, and Internet resources in Appendix E.

CD-ROM

The CD-ROM is a gold mine of information. It begins with a PDF version of the entire contents of this seventh edition of the JavaScript Bible. This version includes bonus chapters covering:

  • Dynamic HTML, data validation, plug-ins, and security

  • Techniques for developing and debugging professional web-based applications

  • Ten full-fledged JavaScript real-world applications

Another treasure trove on the CD-ROM is the Listings folder where you'll find over 300 ready-to-run HTML documents that serve as examples of most of the document object model and JavaScript vocabulary words in Parts III and IV. All of the bonus chapter example listings are also included. You can run these examples with your JavaScript-enabled browser, but be sure to use the index.html page in the Listings folder as a gateway to running the listings. We could have provided you with humorous little sample code fragments out of context, but we think that seeing full-fledged HTML documents (simple though they may be) for employing these concepts is important. We encourage you to manually type the script listings from the tutorial (Part II) of this book. We believe you learn a lot, even by aping listings from the book, as you get used to the rhythms of typing scripts in documents.

Be sure to check out the Chapter 4 listing file called evaluator.html. Many segments of Parts III and IV invite you to try out an object model or language feature with the help of an interactive workbench, called The Evaluator—a JavaScript Bible exclusive! You see instant results and will quickly learn how the feature works.

The Quick Reference from Appendix A is in PDF format on the CD-ROM for you to print out and assemble as a handy reference, if desired. Adobe Reader is also included on the CD-ROM, in case you don't already have it.

Prerequisites to Learning JavaScript

Although this book doesn't demand that you have a great deal of programming experience behind you, the more web pages you've created with HTML, the easier you will find it to understand how JavaScript interacts with the familiar elements you normally place in your pages. Occasionally, you will need to modify HTML tags to take advantage of scripting. If you are familiar with those tags already, the JavaScript enhancements will be simple to digest.

To learn JavaScript, you won't need to know server scripting or how to pass information from a form to a server. The focus here is on client-side scripting, which operates independently of the server after the JavaScript-enhanced HTML page is fully loaded into the browser. However, we strongly believe that a public web page should be operational in the absence of JavaScript, so any dynamic functionality that looks up results or modifies the content of a page should interact with a server-side script fundamentally. After that foundation is laid, we add JavaScript to make a page faster, easier, or more fun. So although you don't need to know server-side scripting in order to learn JavaScript, for serious web work you should either learn a server-side scripting language such as PHP in addition to JavaScript or look for server-side programmers to complement your client-side scripting abilities.

The basic vocabulary of the current HTML standard should be part of your working knowledge. You should also be familiar with some of the latest document markup standards, such as XHTML and Cascading Style Sheets (CSS). Web searches for these terms will uncover numerous tutorials on the subjects.

If you've never programmed before

Don't be put off by the size of this book. JavaScript may not be the easiest language in the world to learn, but believe us, it's a far cry from having to learn a full programming language such as Java or C. Unlike developing a full-fledged monolithic application (such as the productivity programs you buy in stores), JavaScript lets you experiment by writing small snippets of program code to accomplish big things. The JavaScript interpreter built into every scriptable browser does a great deal of the technical work for you.

Programming, at its most basic level, consists of nothing more than writing a series of instructions for the computer to follow. We humans follow instructions all the time, even if we don't realize it. Traveling to a friend's house is a sequence of small instructions: Go three blocks that way; turn left here; turn right there. Amid these instructions are some decisions that we have to make: If the stoplight is red, then stop; if the light is green, then go; if the light is yellow, then floor it! (Just kidding.) Occasionally, we must repeat some operations several times (kind of like having to go around the block until a parking space opens up). A computer program not only contains the main sequence of steps, but it also anticipates what decisions or repetitions may be needed to accomplish the program's goal (such as how to handle the various states of a stoplight or what to do if someone just stole the parking spot you were aiming for).

The initial hurdle of learning to program is becoming comfortable with the way a programming language wants its words and numbers organized in these instructions. Such rules are called syntax, the same as in a living language. Computers aren't very forgiving if you don't communicate with them in the specific language they understand. When speaking to another human, you can flub a sentence's syntax and still have a good chance that the other person will understand you. Not so with computer programming languages. If the syntax isn't perfect (or at least within the language's range of knowledge), the computer has the brazenness to tell you that you have made a syntax error.

The best thing you can do is just accept the syntax errors you receive as learning experiences. Even experienced programmers make mistakes. Every syntax error you get—and every resolution of that error made by rewriting the wayward statement—adds to your knowledge of the language.

If you've done a little programming before

Programming experience in a procedural language, such as BASIC, may actually be a hindrance rather than a help to learning JavaScript. Although you may have an appreciation for precision in syntax, the overall concept of how a program fits into the world is probably radically different from JavaScript's role. Part of this has to do with the typical tasks a script performs (carrying out a very specific task in response to user action within a web page), but a large part also has to do with the nature of object-oriented programming.

If you've programmed in C before

In a typical procedural program, the programmer is responsible for everything that appears on the screen and everything that happens under the hood. When the program first runs, a great deal of code is dedicated to setting up the visual environment. Perhaps the screen contains several text entry fields or clickable buttons. To determine which button a user clicks, the program examines the coordinates of the click and compares those coordinates against a list of all button coordinates on the screen. Program execution then branches out to perform the instructions reserved for clicking in that space.

Object-oriented programming is almost the inverse of that process. A button is considered an object—something tangible. An object has properties, such as its label, size, alignment, and so on. An object may also contain a script. At the same time, the system software and browser, working together, can send a message to an object—depending on what the user does—to trigger the script. For example, if a user clicks in a text entry field, the system/browser tells the field that somebody has clicked there (that is, has set the focus to that field), giving the field the task of deciding what to do about it. That's where the script comes in. The script is connected to the field, and it contains the instructions that the field carries out after the user activates it. Another set of instructions may control what happens when the user types an entry and tabs or clicks out of the field, thereby changing the content of the field.

Some of the scripts you write may seem to be procedural in construction: They contain a simple list of instructions that are carried out in order. But when dealing with data from form elements, these instructions work with the object-based nature of JavaScript. The form is an object; each radio button or text field is an object as well. The script then acts on the properties of those objects to get some work done.

Making the transition from procedural to object-oriented programming may be the most difficult challenge for you. But when the concept clicks—a long, pensive walk might help—so many light bulbs will go on inside your head that you'll think you might glow in the dark. From then on, object orientation will seem to be the only sensible way to program.

By borrowing syntax from Java (which, in turn, is derived from C and C++), JavaScript shares many syntactical characteristics with C. Programmers familiar with C will feel right at home. Operator symbols, conditional structures, and repeat loops follow very much in the C tradition. You will be less concerned about data types in JavaScript than you are in C. In JavaScript, a variable is not restricted to any particular data type.

With so much of JavaScript's syntax familiar to you, you will be able to concentrate on document object model concepts, which may be entirely new to you. You will still need a good grounding in HTML to put your expertise to work in JavaScript.

If you've programmed in Java before

Despite the similarity in their names, the two languages share only surface aspects: loop and conditional constructions, C-like "dot" object references, curly braces for grouping statements, several keywords, and a few other attributes. Variable declarations, however, are quite different, because JavaScript is a loosely typed language. A variable can contain an integer value in one statement and a string in the next (though we're not saying that this is good style). What Java refers to as methods, JavaScript calls methods (when associated with a predefined object) or functions (for scripter-defined actions). JavaScript methods and functions may return values of any type without having to state the data type ahead of time.

Perhaps the most important Java concepts to suppress when writing JavaScript are the object-oriented notions of classes, inheritance, instantiation, and message passing. These aspects are simply non-issues when scripting. At the same time, however, JavaScript's designers knew that you'd have some hard-to-break habits. For example, although JavaScript does not require a semicolon at the end of each statement line, if you type one in your JavaScript source code, the JavaScript interpreter won't balk.

If you've written scripts (or macros) before

Experience with writing scripts in other authoring tools or macros in productivity programs is helpful for grasping a number of JavaScript's concepts. Perhaps the most important concept is the idea of combining a handful of statements to perform a specific task on some data. For example, you can write a macro in Microsoft Excel that performs a data transformation on daily figures that come in from a corporate financial report on another computer. The macro is built into the Macro menu, and you run it by choosing that menu item whenever a new set of figures arrives.

Some modern programming environments, such as Visual Basic, resemble scripting environments in some ways. They present the programmer with an interface builder, which does most of the work of displaying screen objects with which the user will interact. A big part of the programmer's job is to write little bits of code that are executed when a user interacts with those objects. A great deal of the scripting you will do with JavaScript matches that pattern exactly. In fact, those environments resemble the scriptable browser environment in another way: They provide a finite set of predefined objects that have fixed sets of properties and behaviors. This predictability makes learning the entire environment and planning an application easier to accomplish.

Formatting and Naming Conventions

The script listings and words in this book are presented in a monospace font to set them apart from the rest of the text. Because of restrictions in page width, lines of script listings may, from time to time, break unnaturally. In such cases, the remainder of the script appears in the following line, flush with the left margin of the listing, just as it would appear in a text editor with word wrapping turned on. If these line breaks cause you problems when you type a script listing into a document yourself, we encourage you to access the corresponding listing on the CD-ROM to see how it should look when you type it.

As soon as you reach Part III of this book, you won't likely go for more than a page before reading about an object model or language feature that requires a specific minimum version of one browser or another. To make it easier to spot in the text when a particular browser and browser version is required, most browser references consist of an abbreviation and a version number. For example, WinIE5 means Internet Explorer 5 for Windows; NN4 means Netscape Navigator 4 for any operating system; Moz stands for the modern Mozilla browser (from which Firefox, Netscape 6 or later, and Camino are derived); and Safari is Apple's own browser for Mac OS X. If a feature is introduced with a particular version of browser and is supported in subsequent versions, a plus symbol (+) follows the number. For example, a feature marked WinIE5.5+ indicates that Internet Explorer 5.5 for Windows is required at a minimum, but the feature is also available in WinIE8 and probably future WinIE versions. If a feature was implemented in the first release of a modern browser, a plus symbol immediately follows the browser family name, such as Moz+ for all Mozilla-based browsers. Occasionally, a feature or some highlighted behavior applies to only one browser. For example, a feature marked NN4 means that it works only in Netscape Navigator 4.x. A minus sign (e.g., WinIE-) means that the browser does not support the item being discussed.

The format of HTML markup in this edition follows HTML5 coding conventions, but also adheres to many XHTML standards such as all-lowercase tag and attribute names.

NoteTipNote, Tip, Caution, and Cross-Reference icons occasionally appear in the book to flag important points or suggest where to find more information.
CautionCross Reference 


  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint