Praise for Danny Goodman’s JavaScript ™ Bible “JavaScriptTM Bible is the definitive resource in JavaScript programming. I am never more than three feet from my copy.” — Steve Reich, CEO, PageCoders “This book is a must-have for any web developer or programmer.” — Thoma Lile, President, Kanis Technologies, Inc. “Outstanding book. I would recommend this book to anyone interested in learning to develop advanced Web sites. Mr. Goodman did an excellent job of organizing this book and writing it so that even a beginning programmer can understand it.” — Jason Hensley, Director of Internet Services, NetVoice, Inc. “Goodman is always great at delivering clear and concise technical books!” — Dwayne King, Chief Technology Officer, White Horse “JavaScriptTM Bible is well worth the money spent!” — Yen C.Y. Leong, IT Director, Moo Mooltimedia, a member of SmartTransact Group “A must-have book for any internet developer.” — Uri Fremder, Senior Consultant, TopTier Software “I love this book! I use it all the time, and it always delivers. It’s the only JavaScript book I use!” — Jason Badger, Web Developer “Whether you are a professional or a beginner, this is a great book to get.” — Brant Mutch, Web Application Developer, Wells Fargo Card Services, Inc. “I never thought I’d ever teach programming before reading your book [JavaScriptTM Bible]. It’s so simple to use — the Programming Fundamentals section brought it all back! Thank you for such a wonderful book, and for breaking through my programming block!” — Susan Sann Mahon, Certified Lotus Instructor, TechNet Training “I continue to get so much benefit from JavaScriptTM Bible. What an amazing book! Danny Goodman is the greatest!” — Patrick Moss “Danny Goodman is very good at leading the reader into the subject. JavaScript TM Bible has everything we could possibly need.” — Philip Gurdon “An excellent book that builds solidly from whatever level the reader is at. A book that is both witty and educational.” — Dave Vane “I continue to use the book on a daily basis and would be lost without it.” — Mike Warner, Founder, Oak Place Productions “JavaScriptTM Bible is by far the best JavaScript resource I’ve ever seen (and I’ve seen quite a few).” — Robert J. Mirro, Independent Consultant, RJM Consulting “First, I want to thank you for writing THE definitive book on JavaScript. I spent many hours in the computer aisles of bookstores, looking for a text to use for my class, and yours is hands-down the best I’ve seen. It’s now a required text for the course.” — Tom Travers, Instructor, University of New England JavaScript™ Bible 4th Edition Danny Goodman With a foreword by Brendan Eich, JavaScript’s creator Hungry Minds, Inc. New York, NY ✦ Cleveland, OH ✦ Indianapolis, IN JavaScript™ Bible, 4th Edition Published by Hungry Minds, Inc. 909 Third Avenue New York, NY 10022 www.hungryminds.com Copyright © 2001 Danny Goodman. All rights reserved. No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher. Library of Congress Control Number: 200101676 ISBN: 0-7645-3342-8 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 4B/SR/QT/QR/IN Distributed in the United States by Hungry Minds, Inc. Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. for Australia and New Zealand; by TransQuest Publishers Pte Ltd. for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by ICG Muse, Inc. for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de Panama S.A. for Panama; by American Bookshops for Finland. For general information on Hungry Minds’ products and services please contact our Customer Care department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993 or fax 317-572-4002. For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and foreign-language translations, please contact our Customer Care department at 800-434-3422, fax 317-572-4002 or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 Crosspoint Boulevard, Indianapolis, IN 46256. For information on licensing foreign or domestic rights, please contact our Sub-Rights Customer Care department at 650-653-7098. For information on using Hungry Minds’ products and services in the classroom or for ordering examination copies, please contact our Educational Sales department at 800-434-2086 or fax 317-572-4005. For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 650-653-7000 or fax 650-653-7500. For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES. Trademarks: JavaScript is a trademark or registered trademark of Sun Microsystems, Inc. All other trademarks are the property of their respective owners. Hungry Minds, Inc., is not associated with any product or vendor mentioned in this book. is a trademark of Hungry Minds, Inc. About the Author Danny Goodman is the author of numerous critically acclaimed and best-selling books, including The Complete HyperCard Handbook, Danny Goodman’s AppleScript Handbook, and Dynamic HTML: The Definitive Reference. He is a renowned authority and expert teacher of computer scripting languages and is widely known for his “JavaScript Apostle” articles at Netscape’s ViewSource online developer newsletter. His writing style and pedagogy continue to earn praise from readers and teachers around the world. To help keep his finger on the pulse of real-world programming challenges, Goodman frequently lends his touch as consulting programmer and designer to leading-edge World Wide Web and intranet sites from his home base in the San Francisco area. Credits Acquisitions Editor Debra Williams Cauley Project Editor Neil Romanosky Technical Editor David Wall Copy Editors Jerelind Charles Victoria Lee O’Malley Proof Editor Cordelia Heaney Project Coordinator Regina Snyder Graphics and Production Specialists Sean Decker LeAndra Johnson Stephanie Jumper Barry Offringa Kristin Pickett Jill Piscitelli Jeremey Unger Erin Zeltner Quality Control Technicians Laura Albert Valery Bourke Joel Draper Dwight Ramsey Permissions Editor Laura Moss Media Development Specialist Greg Stephens Media Development Coordinator Marisa Pearman Book Designer Kurt Krames Proofreading York Production Services Indexer Johnna VanHoose Dinse Cover Illustrator Kate Shaw Foreword A s JavaScript’s creator, I would like to say a few words about where JavaScript has been, where it is going, and how the book you’re holding will help you to make the most of the language. JavaScript was born out of a desire to let HTML authors write scripts directly in their doc- uments. This may seem obvious now, but in the spring of 1995 it was novel and more than a little at odds with both the conventional wisdom (that HTML should describe static doc- ument structure only) and the Next Big Thing (Java applets, which were hyped as the one true way to enliven and extend Web pages). Once I got past these contentions, JavaScript quickly shaped up along the following lines: ✦ “Java-lite” syntax. Although the “natural language” syntax of HyperTalk was fresh in my mind after a friend lent me The Complete HyperCard Handbook by some fellow named Goodman, the Next Big Thing weighed heavier, especially in light of another goal: script- ing Java applets. If the scripting language resembled Java, then those programmers who made the jump from JavaScript to Java would welcome similarities in syntax. But insist- ing on Java’s class and type declarations, or on a semicolon after each statement when a line ending would do, were out of the question — scripting for most people is about writ- ing short snippets of code, quickly and without fuss. ✦ Events for HTML elements. Buttons should have onClick event handlers. Documents load and unload from windows, so windows should have onLoad and onUnload han- dlers. Users and scripts submit forms: thus the onSubmit handler. Although not initially as flexible as HyperCard’s messages (whose handlers inspired the onEvent naming con- vention), JavaScript events let HTML authors take control of user interaction from remote servers and respond quickly to user gestures and browser actions. With the adoption of the W3C DOM Level 2 event handling recommendations, JavaScript in mod- ern browsers has fully flexible control over events. ✦ Objects without classes. The Self programming language proved the notion of proto- type-based inheritance. For JavaScript, I wanted a single prototype per object (for sim- plicity and efficiency), based by default on the function called using the new operator (for consonance with Java). To avoid distinguishing constructors from methods from functions, all functions receive the object naming them as the property that was called, in the this parameter. Although prototypes didn’t appear until Navigator 3, they were prefigured in Version 2 by quoted text being treated as an object (the String object pro- totype, to which users could attach methods). ✦ Generated HTML. Embedding JavaScript in HTML gave rise to a thought: Let the script speak HTML, as if the emitted text and markup were loaded in place of the script itself. The possibilities went beyond automating current or last-modified dates, to com- puting whole trees of tables where all the repeated structure was rolled up in a scripted loop, while the varying contents to be tabulated came in minimal fashion from JavaScript objects forming a catalog or mini-database. viii JavaScript Bible, 4th Edition At first, I thought JavaScript would most often find use in validating input to HTML forms. But before long, I was surprised to see how many Web designers devised com- pelling applications by way of script-generated HTML and JavaScript objects. It became clear from user demonstration and feedback that Web designers sought to build signifi- cant applications quickly and effectively with just a few images, HTML, and JavaScript. Eventually they demanded that the browser support what is now known as “Dynamic HTML” (one fun link: http://www.javascript-games.org/). As legions of Web authors embraced the authoring power of JavaScript, they, in turn, demonstrated the crucial advantages of a scripting environment over old-school applica- tion development. Not only were the HTML and JavaScript languages comparatively easy to use, but development did not require the programming expertise needed to light all pixels and handle all events as in a big, traditional application. The primacy of JavaScript on the Web today vindicates our early belief in the value of a scripting language for HTML authors. By keeping the “pixel-lighting” bar low, HTML with images has made Web designers out of millions of people. By keeping the “event-handling” bar low, JavaScript has helped many thousands of those designers become programmers. Perhaps the ultimate example of web development’s convergence with application devel- opment is the Mozilla browser, wherein all of the user-interface and even some custom widgets and modular components are implemented entirely using JavaScript, Cascading Style Sheets (CSS), custom XML-based markup languages, and images. JavaScript is also a general language, useful apart from HTML and XML. It has been embedded in servers, authoring tools, browser plug-ins, and other kinds of browsers (for such things as 3D graphical worlds). Its international standard, ECMA-262 ( ISO 16262), has advanced to a Third Edition. But compared to languages such as Perl and even Java, it is still relatively young. Work toward a Fourth Edition of the language, sup- porting optional types, classes, and versioning facilities, progresses within the ECMA technical committee (see the “JS2” proposal to the ECMA technical committee docu- mented at http://www.mozilla.org/js/language/js20/). It is clear to me that JavaScript would not have survived without a creative, loyal, and patient community of developers; I owe them each a huge debt of thanks. Those develop- ers who took up the beta releases of Navigator 2, and disseminated vital workarounds and feature requests by e-mail and net-news, are the language’s godparents. Developer sup- port and feedback continue to make JavaScript the eclectic, rambunctious success it is. The book in your hands compiles thousands of those “developer miles” with the insight of an expert guide and teacher. Danny didn’t know at the time how much inspiration I found in his HyperCard book, but it was on my desk throughout the development of JavaScript in 1995. His energy, compassion, and clear prose helped me keep the goal of “a language for all” in mind. It is enormously gratifying to write the foreword to the fourth edition of this book, which has earned so many “satisfied reader miles.” I highly recommend Danny Goodman’s JavaScript Bible to anyone who wants to learn JavaScript, and especially to those HTML authors who’ve so far written only a few scripts or programs — you’re in for a lifetime of fun on the “scripting road” with a trusty guide at your side. Brendan Eich The Mozilla Organization (http://www.mozilla.org) Preface For nearly 20 years, I have written the books I wished had already been written to help me learn or use a new technology. Whenever possible, I like to get in at the very beginning of a new authoring or programming environment, feel the grow- ing pains, and share with readers the solutions to my struggles. This fourth edition of the JavaScript(tm) Bible represents knowledge and experience accumulated over five years of daily work in JavaScript and a constant monitoring of newsgroups for questions, problems, and challenges facing scripters at all levels. My goal is to help you avoid the same frustration and head scratching I and others have experienced through multiple generations of scriptable browsers. While previous editions of this book focused on the then predominant Netscape Navigator browser, the swing of the browser market share pendulum currently favors Microsoft Internet Explorer. At the same time, Netscape has accomplished the admirable task of reinventing its own browser in light of rapidly advancing industry standards. As a result of both of these trends, this massively revised and expanded fourth edition treats both brands of browsers as equals as far as scripters are con- cerned. You hear my praise and dismay at various scripting features of both browser families. But empowering you to design and write good scripts is my passion, regard- less of browser. Therefore, the book contains details about proprietary and standard implementations to equip you to choose the development path that best fits your content’s audience. If you detect any bias of mine throughout this book, it is a desire, where possible, to write scripts that work on as many browsers as possible. Organization and Features of This Edition Because of the greatly expanded range of vocabularies that scripts may use in the latest browser versions, the biggest change to the structure of the book is in the ref- erence portion. In this edition, you find a greater distinction between the document object model and core JavaScript language reference sections. This new division should help those readers who are primarily interested in only the JavaScript lan- guage (for use in other applications) find what they need more quickly. Here are some details about the book’s structure. Part I 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 x Preface scripters who must develop applications for both single- and cross-platform browser audiences amid rapidly changing standards efforts. Chapter 3 provides the first foray into JavaScript, where you get to write your first practical script. Part II All of Part II is handed over to a tutorial for newcomers to JavaScript. Nine lessons provide you with a gradual path through browser internals, basic programming skills, and genuine JavaScript scripting. With only a couple of clearly labeled items, the lessons cover scripting topics that apply to all scriptable browsers. Exercises fol- low 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 C). 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. By the end of the final lesson, you’ll know how to script multiple frame environments and even create the mouse- rollover image swapping effect that is popular in a lot of Web pages these days. Part III Part III, the largest section of the book, provides in-depth coverage of the document object models as implemented in browsers from the earliest days to today. In all ref- erence chapters, a compatibility chart indicates the browser version that supports each object and object feature. One chapter in particular, Chapter 15, contains ref- erence material that is shared by most of the remaining chapters of Part III. To help you refer back to Chapter 15 from other chapters, a dark tab along the outside edge of the page shows you at a glance where the chapter is located. Additional naviga- tion aids include guide words at the bottoms of most pages to indicate which object and object feature is covered on the page. Part IV Reference information for the core JavaScript language fills Part IV. As with refer- ence chapters of Part III, the JavaScript chapters display browser compatibility charts for every JavaScript language term. Guide words at the bottoms of pages help you find a particular term quickly. Part V In Part V, I get down to the business of deploying JavaScript. Here are the practical aspects of JavaScript, such as Chapter 43’s coverage of client-side form data valida- tion and Chapter 44’s coverage of blending Java applets and plug-ins into pages. Debugging scripts is the focus of Chapter 45, with tips on understanding error mes- sages, building your own debugging tools, and using Netscape’s debugger. Chapter 46 goes into great detail about security issues for JavaScript-enabled applications. Preface xi Dynamic HTML in a cross-browser environment is the subject of Chapter 47, while Chapter 48 introduces you to Microsoft’s behaviors mechanism for Windows. The remaining nine chapters consist of full-fledged applications of JavaScript. These applications are designed not necessarily as plug-and-play modules you can put into your pages right away. Instead, their goal is to demonstrate many of the concepts described earlier in the book by way of real-world examples. New for this edition are some examples based on XML data islands in Internet Explorer for Windows. On the CD-ROM You can find all of the Part V chapters on the CD-ROM that accompanies this book. Part VI Finally, several appendixes at the end of the book provide helpful reference informa- tion. These resources include a JavaScript and Browser Objects Quick Reference in Appendix A, a list of JavaScript reserved words in Appendix B, answers to Part II’s tutorial exercises in Appendix C, and Internet resources in Appendix D. In Appendix E, you also find information on using the CD-ROM that comes with this book. CD-ROM The accompanying CD-ROM contains over 300 ready-to-run HTML documents that serve as examples of most of the document object model and JavaScript vocabu- lary words in Parts III and IV. 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. This page shows you the browsers that are compat- ible with each example listing. I could have provided you with humorous little sam- ple code fragments out of context, but I think that seeing full-fledged HTML documents (simple though they may be) for employing these concepts is impor- tant. I intentionally omitted the script listings from the tutorial part ( Part II ) of this book to encourage you to type the scripts. I believe you learn a lot, even by aping listings from the book, as you get used to the rhythms of typing scripts in docu- ments. You also find listings from Parts I and V on the CD-ROM. The CD-ROM holds another valuable resource: dozens and dozens of Example sec- tions for Parts III and IV. Many of these sections reveal detailed descriptions of HTML listings that illustrate a particular object model or language feature. Even more Example sections 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 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 Acrobat Reader is also included on the CD-ROM so that you can read this .pdf file. Finally, the text of the book is in a .pdf file format on the CD-ROM for easy searching. See Appendix E for information on loading the Acrobat index file. xii Preface 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. Forms and their elements (text fields, buttons, and selection lists) play an espe- cially important role in much of typical JavaScript work. You should be familiar with these elements and their HTML attributes. Fortunately, you won’t need to know about server scripting or passing 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. The basic vocabulary of the current HTML standard should be part of your working knowledge. When we get to using frames, for instance, the focus is on how to script these elements, not on designing pages with them. Microsoft, Netscape, and other online sources provide more detailed explanations of frames. If you’ve never programmed before To someone who learned HTML from a slim guidebook a few years ago, the size of this book must be daunting. JavaScript may not be the easiest language in the world to learn, but believe me, 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 the 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 instruc- tions: Go three blocks that way; turn left here; turn right there. Amid these instruc- tions 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. 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 stop- light 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 instruc- tions. Such rules are called syntax, the same as in a living language. Because com- puters generally are dumb electronic hulks, they aren’t very forgiving if you don’t Preface xiii 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 of the other person’s understanding you fully. Not so with computer programming lan- guages. If the syntax isn’t perfect (or at least within the language’s range of knowl- edge that it can correct), the computer has the brazenness to tell you that you have made a syntax error. The best thing you can do is to just chalk up the syntax errors you receive as learn- ing experiences. Even experienced programmers get them. 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 or Pascal, may almost 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. 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. 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 pro- gram first runs, a great deal of code is dedicated to setting up the visual environ- ment. 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 con- sidered 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. xiv Preface Making the transition from procedural to object-oriented programming may be the most difficult challenge for you. When I was first introduced to object-oriented programming a number of years ago, I didn’t get it at first. But when the concept clicked — a long, pensive walk helped — so many light bulbs went on inside my head that I thought I might glow in the dark. From then on, object orientation seemed to be the only sensible way to program. If you’ve programmed in C before 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 (especially form elements) to put your exper- tise 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 decla- rations, however, are quite different, because JavaScript is a loosely typed lan- guage. A variable can contain an integer value in one statement and a string in the next (though I’m 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 aspects of Java to suppress when writing JavaScript are the object-oriented notions of classes, inheritance, instantiation, and message pass- ing. 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. Preface xv More sophisticated scripting, such as that found in Toolbook or HyperCard, pre- pares you for the object orientation of JavaScript. In those environments, screen objects contain scripts that are executed when a user interacts with those objects. A great deal of the scripting you will do in 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 environ- ment 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 they 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 docu- ment yourself, I 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 min- imum 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 a two-letter abbreviation and a version number. For example, IE5 means Internet Explorer 5 for any operating system; NN6 means Netscape Navigator 6 for any operat- ing system. If a feature is introduced with a particular version of browser and is sup- ported in subsequent versions, a plus symbol (+) follows the number. For example, a feature marked IE4+ indicates that Internet Explorer 4 is required at a minimum, but the feature is also available in IE5, IE5.5, and so on. Occasionally, a feature or some highlighted behavior applies to only one operating system. For example, a feature marked IE4+/Windows means that it works only on Windows versions of Internet Explorer 4 or later. As points of reference, the first scriptable browsers were NN2, IE3/Windows, and IE3.01/Macintosh. Moreover, IE3 for Windows can be equipped with one of two versions of the JScript .dll file. A reference to the earlier version is cited as IE3/J1, while the later version is cited as IE3/J2. You will see this notation pri- marily in the compatibility charts throughout the reference chapters. Note Tip Caution Note, Tip, and Caution icons occasionally appear in the book to flag important points. On the CD-ROM On the CD-ROM icons point you to useful examples and code listings found on this book’s companion CD-ROM. Acknowledgments Before closing, I would like to acknowledge the contributions of many folks who helped make this edition possible: Eric Krock, Tom Pixley, Vidur Apparao, and especially the ever-patient, all-knowing Brendan Eich ( Mozilla); Martin Honnen ( Netscape DevEdge Champion); Tantek Celik ( Microsoft’s Macintosh development group); Brenda McLaughlin, Walt Bruce, Michael Roney, Debra Williams Cauley, Neil Romanosky, Eric Newman, Jerelind Charles, and Victoria Lee O’Malley ( Hungry Minds, Inc.); technical reviewer David Wall; “cookie man” Bill Dortch ( hIdaho Design); Red and his friends ( Mars, Incorporated); and fellow scripters and newsgroup kibitzers, who unwittingly advised me as to where scripters were having trouble with the language. Above all, I want to thank the many readers of the first three editions of this book (with both titles, Danny Goodman’s JavaScript Handbook and JavaScript™ Bible) for investing in this ongoing effort. I wish I had the space here to acknowledge by name so many who have sent e-mail notes and suggestions: Your input has been most welcome and greatly appre- ciated. Now it’s time to get down to the fun of learning JavaScript. Enjoy! A Word from the Publisher The expanded content of this edition far exceeds the number of pages we can bind into a softcover volume. In our goal to deliver to you the author’s comprehensive expertise within these physical limits, we have moved selected chapters of more advanced subjects to the CD-ROM in searchable Acrobat format. We trust that the added value of these unabridged electronic chapters outweighs the associated inconvenience. Contents at a Glance Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi Part I: Getting Started with JavaScript . . . . . . . . . . . . . . . . . . . 1 Chapter 1: JavaScript’s Role in the World Wide Web and Beyond . . . . . . . . . . 3 Chapter 2: Authoring Challenges Amid the Browser Wars . . . . . . . . . . . . . . 13 Chapter 3: Your First JavaScript Script . . . . . . . . . . . . . . . . . . . . . . . . . 21 Part II: JavaScript Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Chapter 4: Browser and Document Objects . . . . . . . . . . . . . . . . . . . . . . 33 Chapter 5: Scripts and HTML Documents . . . . . . . . . . . . . . . . . . . . . . . 57 Chapter 6: Programming Fundamentals, Part I . . . . . . . . . . . . . . . . . . . . 71 Chapter 7: Programming Fundamentals, Part II . . . . . . . . . . . . . . . . . . . . 83 Chapter 8: Window and Document Objects . . . . . . . . . . . . . . . . . . . . . . 99 Chapter 9: Forms and Form Elements . . . . . . . . . . . . . . . . . . . . . . . . . 115 Chapter 10: Strings, Math, and Dates . . . . . . . . . . . . . . . . . . . . . . . . . 131 Chapter 11: Scripting Frames and Multiple Windows . . . . . . . . . . . . . . . . 143 Chapter 12: Images and Dynamic HTML . . . . . . . . . . . . . . . . . . . . . . . 155 Part III: Document Objects Reference . . . . . . . . . . . . . . . . . . 165 Chapter 13: JavaScript Essentials . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Chapter 14: Document Object Model Essentials . . . . . . . . . . . . . . . . . . . 195 Chapter 15: Generic HTML Element Objects . . . . . . . . . . . . . . . . . . . . . 243 Chapter 16: Window and Frame Objects . . . . . . . . . . . . . . . . . . . . . . . 367 Chapter 17: Location and History Objects . . . . . . . . . . . . . . . . . . . . . . 485 Chapter 18: The Document and Body Objects . . . . . . . . . . . . . . . . . . . . 505 Chapter 19: Body Text Objects—Summary . . . . . . . . . . . . . . . . . . . . . 583 Chapter 19: Body Text Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . CD-1 Chapter 20: HTML Directive Objects—Summary . . . . . . . . . . . . . . . . . . 585 Chapter 20: HTML Directive Objects . . . . . . . . . . . . . . . . . . . . . . . . CD-73 Chapter 21: Link and Anchor Objects . . . . . . . . . . . . . . . . . . . . . . . . . 587 Chapter 22: Image, Area, and Map Objects . . . . . . . . . . . . . . . . . . . . . . 601 Chapter 23: The Form and Related Objects . . . . . . . . . . . . . . . . . . . . . 625 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651 Chapter 24: Button Objects Chapter 25: Text-Related Form Objects . . . . . . . . . . . . . . . . . . . . . . . . 673 Chapter 26: Select, Option, and FileUpload Objects . . . . . . . . . . . . . . . . 695 Chapter 27: Table and List Objects—Summary . . . . . . . . . . . . . . . . . . . 721 Chapter 27: Table and List Objects . . . . . . . . . . . . . . . . . . . . . . . . . CD-95 Chapter 28: The Navigator and Other Environment Objects—Summary . . . . . 723 Chapter 28: The Navigator and Other Environment Objects . . . . . . . . . . CD-153 Chapter 29: Event Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725 Chapter 30: Style Sheet and Style Objects . . . . . . . . . . . . . . . . . . . . . . 799 Chapter 31: Positioned Objects—Summary . . . . . . . . . . . . . . . . . . . . . 885 Chapter 31: Positioned Objects . . . . . . . . . . . . . . . . . . . . . . . . . . CD-205 Chapter 32: Embedded Objects—Summary . . . . . . . . . . . . . . . . . . . . . 887 Chapter 32: Embedded Objects . . . . . . . . . . . . . . . . . . . . . . . . . . CD-255 Chapter 33: XML Objects—Summary . . . . . . . . . . . . . . . . . . . . . . . . . 889 Chapter 33: XML Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CD-275 Part IV: JavaScript Core Language Reference . . . . . . . . . . . . . . 891 Chapter 34: The String Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 893 . . . . . . . . . . . . . . . 919 Chapter 35: The Math, Number, and Boolean Objects Chapter 36: The Date Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 937 Chapter 37: The Array Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 Chapter 38: The Regular Expression and RegExp Objects—Summary . . . . . . 983 Chapter 38: The Regular Expression and RegExp Objects . . . . . . . . . . . CD-281 Chapter 39: Control Structures and Exception Handling . . . . . . . . . . . . . . 985 Chapter 40: JavaScript Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 1025 Chapter 41: Functions and Custom Objects . . . . . . . . . . . . . . . . . . . . 1053 Chapter 42: Global Functions and Statements . . . . . . . . . . . . . . . . . . . 1091 Part V: JavaScriptTM Bible, Gold Edition Preview . . . . . . . . . . . 1115 Part VI: Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1125 Appendix A: JavaScript and Browser Object Quick Reference . . . . . . . . . . 1127 Appendix B: JavaScript Reserved Words . . . . . . . . . . . . . . . . . . . . . . 1141 Appendix C: Answers to Tutorial Exercises . . . . . . . . . . . . . . . . . . . . . 1143 Appendix D: JavaScript and DOM Internet Resources . . . . . . . . . . . . . . . 1159 Appendix E: What’s on the CD-ROM . . . . . . . . . . . . . . . . . . . . . . . . . 1163 Appendix F: Examples from Parts III and IV . . . . . . . . . . . . . . . . . . . CD-311 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167 End-User License Agreement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1206 CD-ROM Installation Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . 1209 Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi 1 Part I: Getting Started with JavaScript 1 Chapter 1: JavaScript’s Role in the World Wide Web and Beyond . . . 3 Competition on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Hypertext Markup Language ( HTML) . . . . . . . . . . . . . . . . . . . . . . . 5 CGI Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Of Helpers and Plug-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Java Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 JavaScript: A Language for All . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 LiveScript becomes JavaScript . . . . . . . . . . . . . . . . . . . . . . . 9 The Microsoft world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 JavaScript: The Right Tool for the Right Job . . . . . . . . . . . . . . . . . . 10 Chapter 2: Authoring Challenges Amid the Browser Wars . . . . . . . 13 Leapfrog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Duck and Cover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Compatibility Issues Today . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Separating language from objects . . . . . . . . . . . . . . . . . . . . . 15 Core language standard . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Document object model . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Cascading Style Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Dynamic HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 . . . . . . . . . . . . . . . . . . . . . . . . . 19 Developing a Scripting Strategy Chapter 3: Your First JavaScript Script . . . . . . . . . . . . . . . . . . . 21 The Software Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Choosing a text editor Choosing a browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 . . . . . . . . . . . . . . . . . . . . 22 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 MacOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Reloading issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Setting up Your Authoring Environment xx JavaScript Bible, 4th Edition What Your First Script Will Do . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Entering Your First Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Examining the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 The 3. Save the document with the name script1.htm. ( This is the lowest common denominator filenaming convention for Windows 3.1 — feel free to use an .html extension if your operating system allows it.) 4. Switch to your browser. 5. Choose Open (or Open File on some browsers) from the File menu and select script1.htm. (On some browsers, you have to click a Browse button to reach the File dialog box.) If you typed all lines as directed, the document in the browser window should look like the one in Figure 3-3 (with minor differences for your computer’s operating sys- tem and browser version). If the browser indicates that a mistake exists somewhere as the document loads, don’t do anything about it for now. (Click the OK button if you see a script error dialog box.) Let’s first examine the details of the entire docu- ment so you understand some of the finer points of what the script is doing. Examining the Script You do not need to memorize any of the commands or syntax discussed in this sec- tion. Instead, relax and watch how the lines of the script become what you see in the browser. In Listing 3-1, all of the lines up to the tag pair. These tags alert the browser program to begin interpreting all the text between these tags as a script. Because other scripting languages (such as Microsoft’s VBScript) can take advantage of these script tags, you must specify the precise name of the language in which the enclosed code is written. Therefore, when the browser receives this signal that your script uses the JavaScript language, it employs its built-in JavaScript inter- preter to handle the code. You can find parallels to this setup in real life: If you have a French interpreter at your side, you need to know that the person with whom you’re conversing also knows French. If you encounter someone from Russia, the French interpreter can’t help you. Similarly, if your browser has only a JavaScript interpreter inside, it can’t understand code written in VBScript. Now is a good time to instill an aspect of JavaScript that will be important to you throughout all your scripting ventures: JavaScript is case-sensitive. Therefore, you must enter any item in your script that uses a JavaScript word with the correct uppercase and lowercase letters. Your HTML tags (including the tags. Do not put these comment lines above the tag and expect them to work. One more issue about the script-hiding comment lines in this book. To save space on the page, most examples do not have comment lines inserted in them. But as you can see in the full-fledged application examples from Chapters 49 through 57 on the CD-ROM, the comment lines are where they should be. For any pages you produce for public consumption, always encase your script lines inside these comments. Displaying some text Both script lines in Listing 3-1 use one of the possible actions a script can ask a doc- ument to perform (document.write(), meaning display text in the current docu- ment). You learn more about the document object in Chapter 18. Whenever you ask an object (a document in this case) to perform a task for you, the name of the task is always followed by a set of parentheses. In some cases — the write() task, for example — JavaScript needs to know what information it should act on. That information (called a parameter) goes inside parentheses after the name of the task. Thus, if you want to write the name of the first U.S. president to a document, the command to do so is document.write(“George Washington”) 30 Part I ✦ Getting Started with JavaScript The line of text that the script writes starts with some static text (“This browser is version”) and adds some evaluated text (the version of the browser) to it. The writing continues with more static text that includes an HTML tag (“of ”), more evaluated text (the name of the browser application), and an HTML closing tag and the sentence’s period (“.”). JavaScript uses the plus symbol (+) to join (con- catenate) text components into a larger, single string of text characters to be written by the document. Neither JavaScript nor the + symbol knows anything about words and spaces, so the script is responsible for making sure that the proper spaces are passed along as part of the parameters. Notice, therefore, that an extra space exists after the word “version” in the first document.write() parameter, and extra spaces exist on both sides of “of” in the second document.write() parameter. To fetch the information about the browser version and name for your parameters, you call upon JavaScript to extract the corresponding properties from the naviga- tor object. You extract a property by appending the property name to the object name (navigator in this case) and separating the two names with a period. If you’re searching for some English to mentally assign to this scheme as you read it, start from the right side and call the right item a property “of” the left side: the appVersion property of the navigator object. This dot syntax looks a great deal like the document.write() task, but a property name does not have parentheses after it. In any case, the reference to the property in the script tells JavaScript to insert the value of that property in the spot where the call is made. For your first attempt at the script, JavaScript substitutes the internal information about the browser as part of the text string that gets written to the document. Have Some Fun If you encounter an error in your first attempt at loading this document into your browser, go back to the text editor and check the lines of the script section against Listing 3-1, looking carefully at each line in light of the explanations. There may be a single character out of place, a lowercase letter where an uppercase one belongs, or a quote or parenthesis missing. Make necessary repairs, switch to your browser, and click Reload. To see how dynamic the script in script1.htm is, go back into the text editor and replace the word “browser” with “client software.” Save, switch, and reload to see how the script changes the text in the document. Feel free to substitute other text for the quoted text in the document.write() statement. Or, add more text with additional document.write() statements. The parameters to document.write() are HTML text, so you can even write “
” to make a line break. Always be sure to save, switch, and reload to see the results of your handiwork. ✦ ✦ ✦ JavaScript Tutorial P A R T IIII ✦ ✦ ✦ ✦ In This Part Chapter 4 Browser and Document Objects Chapter 5 Scripts and HTML Documents Chapter 6 Programming Fundamentals, Part I Chapter 7 Programming Fundamentals, Part II Chapter 8 Window and Document Objects Chapter 9 Forms and Form Elements Chapter 10 Strings, Math, and Dates Chapter 11 Scripting Frames and Multiple Windows Chapter 12 Images and Dynamic HTML ✦ ✦ ✦ ✦ 44C H A P T E R ✦ ✦ ✦ ✦ In This Chapter What client-side scripts do What happens when a document loads How the browser creates objects How scripts refer to objects How to find out what is scriptable in an object ✦ ✦ ✦ ✦ Browser and Document Objects This chapter marks the first of nine tutorial chapters (which compose Part II ) tailored to Web authors who have at least basic grounding in HTML concepts. In this chap- ter, you see several practical applications of JavaScript and begin to see how a JavaScript-enabled browser turns familiar HTML elements into objects that your scripts control. Most of what you learn throughout the tutorial can be applied to all scriptable browsers ( back to Navigator 2 and Internet Explorer 3). I clearly label a handful of fancy features that require recent browser versions. Scripts Run the Show If you have authored Web pages with HTML, you are familiar with how HTML tags influence the way content is rendered on a page when viewed in the browser. As the page loads, the browser recognizes angle-bracketed tags as formatting instructions. Instructions are read from the top of the docu- ment downward, and elements defined in the HTML document appear onscreen in the same order in which they appear in the document’s source code. As an author, you do a little work one time and up front — adding the tags to text content — and the browser does a lot more work every time a visitor loads the page into a browser. Assume for a moment that one of the elements on the page is a text input field inside a form. The user is supposed to enter some text in the text field and then click the Submit button to send that information back to the Web server. If that informa- tion must be an Internet e-mail address, how do you ensure the user includes the “@” symbol in the address? 34 Part II ✦ JavaScript Tutorial One way is to have a Common Gateway Interface (CGI ) program on the server inspect the submitted form data after the user clicks the Submit button and the form information is transferred to the server. If the user omits or forgets the “@” symbol, the CGI program serves the page back to the browser — but this time with an instruction to include the symbol in the address. Nothing is wrong with this exchange, but it means a significant delay for the user to find out that the address does not contain the crucial symbol. Moreover, the Web server has to expend some of its resources to perform the validation and communicate back to the visitor. If the Web site is a busy one, the server may try to perform hundreds of these validations at any given moment, probably slowing the response time to the user even more. Now imagine that the document containing that text input field has some intelli- gence built into it that makes sure the text field entry contains the “@” symbol before ever submitting one bit ( literally!) of data to the server. That kind of intelli- gence would have to be embedded in the document in some fashion — downloaded with the page’s content so it can stand ready to jump into action when called upon. The browser must know how to run that embedded program. Some user action must start the program, perhaps when the user clicks the Submit button. If the pro- gram runs inside the browser and detects a lack of the “@” symbol, an alert mes- sage should appear to bring the problem to the user’s attention. The same program also should be capable of deciding if the actual submission can proceed or if it should wait until a valid e-mail address is entered into the field. This kind of pre-submission data entry validation is but one of the practical ways JavaScript adds intelligence to an HTML document. Looking at this example, you might recognize that a script must know how to look into what is typed in a text field; a script must also know how to let a submission continue or how to abort the submission. A browser capable of running JavaScript programs conveniently treats elements such as the text field as objects. A JavaScript script controls the action and behavior of objects — most of which you see on the screen in the browser window. JavaScript in Action By adding lines of JavaScript code to your HTML documents, you control onscreen objects in whatever way your applications require. To give you an idea of the scope of applications you can create with JavaScript, I show you several applications on the CD-ROM (in the folders for Chapters 48 through 57). I strongly suggest you open the applications and play with them in your browser as they are described in the next several pages. You can find links to the application files from the CD-ROM on the page tutor1.htm in the example listings folder. Interactive user interfaces HTML hyperlinks do a fine job, but they’re not necessarily the most engaging way to present a table of contents for a large site or document. With a bit of JavaScript, you can create an interactive, expandable table of contents listing that displays the Chapter 4 ✦ Browser and Document Objects 35 hierarchy of a large body of material (see Figure 4-1). Just like the text listings (or tree views) in operating system file management windows, the expandable table of contents lets the user see as much or as little as possible while displaying the big picture of the entire data collection. Figure 4-1: An expandable table of contents Click a gray widget icon to expand the items underneath. An endpoint item has an orange and black widget icon. Items in the outline can be links to other pages or descriptive information. You also maintain the same kind of font control over each entry, as expected from HTML. While such outlines have been created with server CGIs in the past, the response time between clicks is terribly slow. By placing all of the smarts behind the outline inside the page, it downloads once and runs quickly after each click. As demonstrated in the detailed description of this outline in the application Outline-Style Table of Contents (Chapter 52 on the CD-ROM ), you can implement the scriptable workings within straight HTML for Navigator 2 and 3 — although limi- tations in page rendering require rewriting the page after each click. Internet Explorer 4+ and Navigator 6+ automatically reflow the page in response to changes of content, turning this outliner into a truly dynamic HTML application. Either way you do it, the quick response and action on the screen makes for a more engaging experience for Web surfers who are in a hurry to scout your site. 36 Part II ✦ JavaScript Tutorial Small data lookup A common application on the Web is having a CGI program present a page that visi- tors use to access large databases on the server. Large data collections are best left on the server where search engines and other technologies are the best fit. But if your page acts as a front end to a small data collection lookup, you can consider embedding that data collection in the document (out of view) and letting JavaScript act as the intermediary between user and data. I do just that in a Social Security prefix lookup system shown in Figure 4-2. I convert a printed table of about 55 entries into a JavaScript list that occupies only a few hundred bytes. When the visitor types the three-character prefix of his or her Social Security number into the field and clicks the Search button, a script behind the scenes compares that number against the 55 or so ranges in the table. When the script finds a match, it displays the corresponding state of registration in a second field. Figure 4-2: Looking up data in a small table If the application were stored on the server and the data stored in a server database, each click of the Search button would mean a delay of many seconds as the server processed the request, got the data from the database, and reformulated the page with the result for the user. Built instead as a JavaScript application, once the page downloads the first time, scripts perform all lookups instantaneously. Chapter 4 ✦ Browser and Document Objects 37 Forms validation I’ve already used data entry form validation as an example of when JavaScript is a good fit. In fact, the data entry field in the Social Security lookup page (see Figure 4-2) includes scripting to check the validity of the entered number. Just as a CGI program for this task has to verify that the entry is a three-digit number, so, too, must the JavaScript program verify the entered value. If a mistake appears in the entry — perhaps a finger slips and hits a letter key — the visitor is advised of the problem and directed to try another entry. The validation script even prese- lects the text in the entry field for the visitor so that typing a new value replaces the old one. Interactive data JavaScript opens opportunities for turning static information into interactive infor- mation. Figure 4-3 shows a graphical calculator for determining the value of an elec- trical component (called a resistor) whose only markings are colored bars. Figure 4-3: An interactive graphical calculator The image in the bottom half of the page is composed of seven images in vertical slices all bunched up against each other. Four slices display the colored bands, while the remaining three slices contain the ends of the resistor and the spacer between groups of bands. As the visitor selects a color from a pop-up list near the 38 Part II ✦ JavaScript Tutorial top, the associated image slice changes to the selected color and the resistance value is calculated and displayed. Again, once the page is loaded, response time is instantaneous. Conversely, a server-based version of this calculator would take many seconds between color changes. Moreover, JavaScript provides the power to preload all possible images into the browser cache while the main page loads. Therefore, with only a slight extra delay to download all images with the page, no further delay occurs when a visitor chooses a new color. Not only is the application practical (for its intended audience), but it’s just plain fun to play with. Multiple frames While frames are the domain of HTML, they suddenly become more powerful with some JavaScript behind them. The Decision Helper application shown in Figure 4-4 takes this notion to the extreme. Figure 4-4: The Decision Helper The Decision Helper is a full-fledged application that includes four input screens and one screen that displays the results of some fairly complex calculations based on the input screens. Results are shown both in numbers and in a bar graph form, as displayed in Figure 4-4. Interaction among the three frames requires JavaScript. For example, suppose the user clicks one of the directional arrows in the top-left frame. Not only does the top- right frame change to another document, but the instructions document in the bot- tom frame also shifts to the anchor point that parallels the content of the input Chapter 4 ✦ Browser and Document Objects 39 screen. Scripting behind the top-right frame documents uses various techniques to preserve entry information as the user navigates through the sequence of input pages. These are the same techniques you might use to build an online product cat- alog and shopping cart — accumulating the customer’s selections from various cat- alog pages and then bringing them together in the checkout order form. Certainly you could fashion this application out of a CGI program on the server. But the high level of interaction and calculation required would turn this now speedy application into a glacially slow exchange of information between user and server. Dynamic HTML Starting with the version 4 browsers from both Netscape and Microsoft, you can modify more and more content on the page with the help of client-side scripts. In Figure 4-5, for example, scripts in the page control the dragging of map pieces in the puzzle. Highlighted colors change as you click the state maps, instruction panels fly in from the edge of the screen, and another item appears when you place all the states in their proper positions. Figure 4-5: A map game in scriptable Dynamic HTML The browser feature that makes this level of script control possible is Dynamic HTML (DHTML). JavaScript becomes the vital connection between the user and dynamically respositionable elements on the screen. Not even a program on the 40 Part II ✦ JavaScript Tutorial server could help this application because you need immediate programmatic con- trol in the page to respond to user mouse motion and instantaneous changes to screen elements. When to use JavaScript The preceding examples demonstrate a wide range of applications for JavaScript, but by no means do they come close to exhausting JavaScript’s possibilities. When faced with a Web application task, I look to client-side JavaScript for help with the following requirements: ✦ Data entry validation: If form fields need to be filled out for processing on the server, I let client-side scripts prequalify the data entered by the user. ✦ Serverless CGIs: I use this term to describe processes that, were it not for JavaScript, would be programmed as CGIs on the server, yielding slow perfor- mance because of the interactivity required between the program and user. This includes tasks such as small data collection lookup, modification of images, and generation of HTML in other frames and windows based on user input. ✦ Dynamic HTML interactivity: It’s one thing to use DHTML’s capabilities to precisely position elements on the page — you don’t need scripting for that. But if you intend to make the content dance on the page, scripting makes that happen. ✦ CGI prototyping: Sometimes you may want a CGI program to be at the root of your application because it reduces the potential incompatibilities among browser brands and versions. It may be easier to create a prototype of the CGI in client-side JavaScript. Use this opportunity to polish the user interface before implementing the application as a CGI. ✦ Offloading a busy server: If you have a highly trafficked Web site, it may be beneficial to convert frequently used CGI processes to client-side JavaScript scripts. Once a page is downloaded, the server is free to serve other visitors. Not only does this lighten server load, but users also experience quicker response to the application embedded in the page. ✦ Adding life to otherwise dead pages: HTML by itself is pretty “flat.” Adding a blinking chunk of text doesn’t help much; animated GIF images more often dis- tract from, rather than contribute to, the user experience at your site. But if you can dream up ways to add some interactive zip to your page, it may engage the user and encourage a recommendation to friends or repeat visits. ✦ Creating “Web pages that think”: If you let your imagination soar, you may develop new, intriguing ways to make your pages appear “smart.” For exam- ple, in the application Intelligent “Updated” Flags (Chapter 54), you see how (without a server CGI or database) an HTML page can “remember” when a vis- itor last came to the page. Then any items that have been updated since the Chapter 4 ✦ Browser and Document Objects 41 last visit — regardless of the number of updates you’ve done to the page — are flagged for that visitor. That’s the kind of subtle, thinking Web page that best displays JavaScript’s powers. The Document Object Model Before you can truly start scripting, you should have a good feel for the kinds of objects you will be scripting. A scriptable browser does a lot of the work of creating software objects that generally represent the visible objects you see in an HTML page in the browser window. Obvious objects include form controls (text boxes and buttons) and (in recent browsers) images. However, there may be other objects that aren’t so obvious by looking at a page, but which make perfect sense when you consider the HTML tags used to generate a page’s content — frames of a frameset, for example. To help scripts control these objects — and to help authors see some method to the madness of potentially dozens of objects on a page — the browser makers define a document object model (DOM). A model is like a prototype or plan for the organiza- tion of objects on a page. Object models implemented in browsers have grown rapidly with each generation of browser. Moreover, Microsoft and Netscape have added their own touches from time to time in a competitive features race. The lack of compatibility among browser versions and brands can drive scripters to distraction, especially if (at the outset) they learn the object model only of the latest version of only one brand — unaware of limits in earlier browsers or those from other makers. Proprietary and Standard Object Models Object model features that are proprietary to one browser version and/or brand are per- fectly usable provided you know that your audience uses that brand or version exclusively (for example, in a corporate environment where a browser version might be mandated for all employees). If you develop in this kind of controlled environment, then be assured that browser-specific features are covered in the reference portions of this book. An industry standards effort (by the W3C) has begun specifying a common set of object model features and syntax that provide more flexibility than the original implementations. The biggest improvement is that every HTML element becomes an object that scripts can manipulate (a feature also found in IE4’s object model). This DOM, built upon the original object model you learn in this tutorial, is implemented in varying degrees of completion in IE5+ and NN6+ (the latter offering a much more complete W3C DOM implementation). The scripter’s dream is that one day W3C DOM-compatible browsers will be the majority of the installed base, and creating cross-browser, highly dynamic pages will be easier than today. In the meantime, you have lots of fundamentals to learn — knowledge that you’ll use for many years to come. 42 Part II ✦ JavaScript Tutorial All is not lost, however. This tutorial focuses on the document object model that you can find in every scriptable browser. Figure 4-6 shows a map of the lowest com- mon denominator object model, which is safe to use on all browsers. At this stage of the learning process, it is not important to memorize the model but rather to get a general feel for what’s going on. window frame self top parent history document location link form anchor text radio button select textarea checkbox reset option password submit Figure 4-6: Lowest common denominator document object model for all scriptable browsers One misconception you must avoid at the outset is that the model shown in Figure 4-6 is the model for every document that loads into the browser. On the contrary — it represents an idealized version of a document that includes one of every possible type of object that the browser knows. In a moment, I will show you how the docu- ment object model stored in the browser at any given instant reflects the HTML in the document. But for now, I want to impress an important aspect of the structure of the idealized model: its hierarchy. Containment hierarchy Notice in Figure 4-6 that objects are grouped together in various levels designated by the density of the gray background. Objects are organized in a hierarchy, not unlike the hierarchy of a company’s organization chart of job positions. At the top is the president. Reporting to the president are several vice presidents. One of the vice presidents manages a sales force that is divided into geographical regions. Each region has a manager who reports to the vice president of sales; each region Chapter 4 ✦ Browser and Document Objects 43 then has several salespeople. If the president wants to communicate to a salesper- son who handles a big account, the protocol dictates that the president should route the message through the hierarchy — to the vice president of sales; to the sales manager; to the salesperson. The hierarchy clearly defines each unit’s role and relationship to the other units. This hierarchical structure applies to the organization of objects in a document. Allow me to highlight the key objects in Figure 4-6 and explain their relationships to others. ✦ Window object: At the top of the hierarchy is the window. This object repre- sents the content area of the browser window where HTML documents appear. In a multiple-frame environment, each frame is also a window ( but don’t concern yourself with this just yet). Because all document action takes place inside the window, it is the outermost element of the object hierarchy. Its physical borders contain the document. ✦ Document object: Each HTML document that gets loaded into a window becomes a document object. Its position in the object hierarchy is an impor- tant one, as you can see in Figure 4-6. The document object contains most of the other kinds of objects in the model. This makes perfect sense when you think about it: The document contains the content that you are likely to script. ✦ Form object: Users don’t see the beginning and ending of forms on a page, only their elements. But a form is a distinct grouping of content inside an HTML document. Everything that is inside the
...
tag set is part of the form object. A document might have more than one pair of
tags if dictated by the page design. If so, the map of the objects for that particular document has two form objects instead of the one that appears in Figure 4-6. ✦ Form control elements: Just as your HTML defines form elements within the confines of the ...
tag pair, so does a form object contain all the elements defined for that object. Each one of those form elements — text fields, buttons, radio buttons, checkboxes, and the like — is a separate object. Unlike the one-of-everything model shown in Figure 4-6, the precise model for any document depends on the HTML tags in the document. When a Document Loads Programming languages, such as JavaScript, are convenient intermediaries between your mental image of how a program works and the true inner workings of the com- puter. Inside the machine, every word of a program code listing influences the stor- age and movement of bits (the legendary 1s and 0s of the computer’s binary universe) from one RAM storage slot to another. Languages and object models are inside the computer (or, in the case of JavaScript, inside the browser’s area of the computer) to make it easier for programmers to visualize how a program works and what its results will be. The relationship reminds me a lot of knowing how to drive an automobile from point A to point B without knowing exactly how an internal 44 Part II ✦ JavaScript Tutorial combustion engine, steering linkages, and all that other internal “stuff” works. By controlling high-level objects such as the ignition key, gearshift, gas pedal, brake, and steering wheel, I can get the results I need. Of course, programming is not exactly like driving a car with an automatic transmis- sion. Even scripting requires the equivalent of opening the hood and perhaps know- ing how to check the transmission fluid or change the oil. Therefore, now it’s time to open the hood and watch what happens to the document object model as a page loads into the browser. A simple document Figure 4-7 shows the HTML and corresponding object model for a very simple docu- ment. When this page loads, the browser maintains in its memory a map of the objects generated by the HTML tags in the document. The window object is always there for every document. Every window object also contains an object called the location object (it stores information about the URL of the document being loaded). I’ll skip that object for now, but acknowledge its presence (as a dimmed box in the diagram) because it is part of the model in the browser memory. Finally, because a document has been loaded, the browser generates a document object in its current map. Simple Doc

Howdy

Window Location Document Figure 4-7: A simple document and object map Note In IE4+ and the W3C DOM, every HTML element (such as the H1 element of Figure 4-7) becomes an object contained by the document. But this tutorial observes the original model, which turns only a handful (albeit an important handful) of HTML elements into scriptable objects. Add a form Now, I modify the HTML file to include a blank
tag set and reload the docu- ment. Figure 4-8 shows what happens to both the HTML (changes in boldface) and the object map as constructed by the browser. Even though no content appears in the form, the tags are enough to tell the browser to create that form object. Chapter 4 ✦ Browser and Document Objects 45 Also note that the form object is contained by the document in the hierarchy of objects in the current map. This mirrors the structure of the idealized map shown in Figure 4-6. Simple Doc

Howdy

Figure 4-8: Adding a form Window Location Document Form Add a text input element I modify and reload the HTML file again, this time including an tag that defines the text field form element shown in Figure 4-9. As mentioned earlier, the containment structure of the HTML (the tag goes inside a
tag set) is reflected in the object map for the revised document. Therefore, the window con- tains a document; the document contains a form; and the form contains a text input element. Simple Doc

Howdy

Window Location Document Form Text Figure 4-9: Adding a text input element to the form 46 Part II ✦ JavaScript Tutorial Add a button element The last modification I make to the file is to add a button input element to the same form as the one that holds the text input element (see Figure 4-10). Notice that the HTML for the button is contained by the same
tag set as the text field. As a result, the object map hierarchy shows both the text field and button contained by the same form object. If the map were a corporate organization chart, the employ- ees represented by the Text and Button boxes would be at the same level reporting to the same boss. Simple Doc

Howdy

Window Location Document Form Text Button Figure 4-10: Adding a button element to the same form Now that you see how objects are created in memory in response to HTML tags, the next step is to figure out how scripts can communicate with these objects. After all, scripting is mostly about controlling these objects. Object References After a document is loaded into the browser, all of its objects are safely stored in memory in the containment hierarchy structure specified by the browser’s docu- ment object model. For a script to control one of those objects, there must be a way to communicate with an object and find out something about it such as, “Hey, Mr. Text Field, what did the user type?” Chapter 4 ✦ Browser and Document Objects 47 The JavaScript language uses the containment hierarchy structure to let scripts get in touch with any object in a document. For a moment, pretend you are the browser with a document loaded into your memory. You have this road map of objects handy. If a script needs you to locate one of those objects, it would be a big help if the script showed you what route to follow in the map to reach that object. That is precisely what an object reference in a script does for the browser. Object naming The biggest aid in creating script references to objects is assigning names to every scriptable object in your HTML. Scriptable browsers, such as modern versions of Navigator and Internet Explorer, acknowledge an optional tag attribute called NAME. This attribute enables you to assign a unique name to each object. Here are some examples of NAME attributes added to typical tags:
The only rules about object names (also called identifiers) are that they ✦ May not contain spaces ✦ Should not contain punctuation except for the underscore character ✦ Must be inside quotes when assigned to the NAME attribute ✦ Must not start with a numeric character Think of assigning names the same as sticking nametags on everyone attending a conference meeting. The name of the object, however, is only one part of the actual reference that the browser needs to locate the object. For each object, the refer- ence must include the steps along the object hierarchy from the top down to the object — no matter how many levels of containment are involved. In other words, the browser cannot pick out an object by name only. A reference includes the names of each object along the path from the window to the object. In the JavaScript language, each successive object name along the route is separated from another by a period. To demonstrate what real references look like within the context of an object model you’ve already seen, I retrace the same model steps shown earlier but this time I show the reference to each object as the document acquires more objects. 48 Part II ✦ JavaScript Tutorial NAME versus ID Attributes The HTML 4.0 specification introduces a new way to assign an identifier to HTML elements: the ID attribute. The ID attribute is helpful for some aspects of Cascading Style Sheets (CSS) and Dynamic HTML. Even so, the NAME attribute is still required for common denom- inator elements covered in this tutorial — FRAME, FORM, and INPUT elements, for example. The newest browsers can access an element by name or ID, but authors typically use the ID attribute for HTML element objects not shown in Figure 4-6. You can read more about the ID attribute (and id property) in Chapter 15 after you finish the tutorial. A simple document I start with the model whose only objects are the window (and its location object) and document from the simple HTML file. Figure 4-11 shows the object map and ref- erences for the two main objects. Every document resides in a window, so to refer- ence the window object you start with window. Also fixed in this reference is the document because there can be only one document per window (or frame). Therefore, a reference to the document object is window.document. window Window Location window.document Document Figure 4-11: References to the window and document Add a form Modifying the document to include the empty tag generates the form object in the map. If I do the job right, the tag also includes a NAME attribute. The reference to the form object, as shown in Figure 4-12, starts with the window, wends through the document, and reaches the form, which I call by name: window.document.formName (the italics meaning that in a real script, I would sub- stitute the form’s name for formName). Chapter 4 ✦ Browser and Document Objects 49 window Window Location window.document Document window.document.formName Form Figure 4-12: Reference to the form object Add a text input element As the hierarchy gets deeper, the object reference gets longer. In Figure 4-13, I add a text input object to the form. The reference to this deeply nested object still starts at the window level and works its way down to the name I assigned to the object in its tag: window.document.formName.textName. window Window Location window.document Document window.document.formName Form window.document.formName.textName Text Figure 4-13: Reference to the text field object Add a button element When I add a button to the same form as the text object, the reference stays the same length (see Figure 4-14). All that changes is the last part of the reference where the button name goes in place of the text field name: window.document.formName.buttonName. 50 Part II ✦ JavaScript Tutorial window Window Location window.document Document window.document.formName window.document.formName.textName window.document.formName.buttonName Figure 4-14: Reference to the button object Form Text Button About the Dot Syntax JavaScript uses the period to separate components of a hierarchical reference. This convention is adopted from Java, which, in turn, based this formatting on the C lan- guage. Every reference typically starts with the most global scope — the window for client-side JavaScript — and narrows focus with each “dot” (.) delimiter. If you have not programmed before, don’t be put off by the dot syntax. You are probably already using it, such as when you access Usenet newsgroups. The methodology for organizing the thousands of newsgroups is to group them in a hierarchy that makes it relatively easy to both find a newsgroup and visualize where the newsgroup you’re currently reading is located in the scheme of things. Newsgroup organization model Let me briefly dissect a typical newsgroup address to help you understand dot syn- tax: rec.sport.skating.inline. The first entry (at the left edge) defines the basic group — recreation — among all the newsgroup categories. Other group cate- gories, such as comp and alt, have their own sections and do not overlap with what goes on in the rec section. Within the rec section are dozens of subsections, one of which is sport. That name distinguishes all the sport-related groups from, say, the automobile or music groups within recreational newsgroups. Chapter 4 ✦ Browser and Document Objects 51 Like most broad newsgroup categories, rec.sport has many subcategories, with each one devoted to a particular sport. In this case, it is skating. Other sport news- groups include rec.sport.rugby and rec.sport.snowboarding. Even within the rec.sport.skating category, a further subdivision exists to help narrow the sub- ject matter for participants. Therefore, a separate newsgroup just for inline skaters exists, just as a group for roller-skating exists (rec.sport.skating.roller). As a narrower definition is needed for a category, a new level is formed by adding a dot and a word to differentiate that subgroup from the thousands of newsgroups on the Net. When you ask your newsgroup software to view messages in the rec.sport.skating.inline group, you’re giving it a map to follow in the news- group hierarchy to go directly to a single newsgroup. Another benefit of this syntactical method is that names for subcategories can be reused within other categories, if necessary. For example, with this naming scheme, it is possible to have two similarly named subcategories in two separate newsgroup classifications (such as rec.radio.scanners and alt.radio.scanners). When you ask to visit one, the hierarchical address, starting with the rec or alt classifi- cation, ensures you get to the desired place. Neither collection of messages is auto- matically connected with the other (although subscribers frequently cross-post to both newsgroups). For complete newbies to the Net, this dot syntax can be intimidating. Because the system was designed to run on UNIX servers (the UNIX operating system is written in C), the application of a C-like syntax for newsgroup addressing is hardly surprising. What Defines an Object? When an HTML tag defines an object in the source code, the browser creates a slot for that object in memory as the page loads. But an object is far more complex internally than, say, a mere number stored in memory. The purpose of an object is to represent some “thing.” Because in JavaScript you deal with items that appear in a browser window, an object may be an input text field, a button, or the whole HTML document. Outside of the pared-down world of a JavaScript browser, an object can also represent abstract entities, such as a calendar program’s appoint- ment entry or a layer of graphical shapes in a drawing program. Every object is unique in some way, even if two or more objects look identical to you in the browser. Three very important facets of an object define what it is, what it looks like, how it behaves, and how scripts control it. Those three facets are prop- erties, methods, and event handlers. They play such key roles in your future JavaScript efforts that the Quick Reference in Appendix A summarizes the proper- ties, methods, and event handlers for each object in the object models imple- mented in various browser generations. You might want to take a quick peek at that road map of the original object model if for no other reason than to gain an appreci- ation for the size of the scripting vocabulary that this tutorial covers. 52 Part II ✦ JavaScript Tutorial Properties Any physical object you hold in your hand has a collection of characteristics that defines it. A coin, for example, has shape, diameter, thickness, color, weight, embossed images on each side, and any number of other attributes that distinguish it from, say, a feather. Each of those features is called a property. Each property has a value of some kind attached to it (even if the value is empty or null). For example, the shape property of a coin might be “circle” — in this case, a text value. In con- trast, the denomination property is most likely a numeric value. You may not have known it, but if you’ve written HTML for use in a scriptable browser, you have set object properties without writing one iota of JavaScript. Tag attributes are the most common way to set an HTML object’s initial properties. The presence of JavaScript often adds optional attributes whose initial values you can set when the document loads. For example, the following HTML tag defines a button object that assigns two property values: In JavaScript parlance, then, the name property holds the word “clicker,” while the value property is the text that appears on the button label, “Hit Me. . . .” In truth, a button has more properties than just these, but you don’t have to set every prop- erty for every object. Most properties have default values that are automatically assigned if nothing special is set in the HTML or later from a script. The contents of some properties can change while a document is loaded and the user interacts with the page. Consider the following text input tag: The name property of this object is the word “entry.” When the page loads, the text of the VALUE attribute setting is placed in the text field — the automatic behavior of an HTML text field when the VALUE attribute is specified. But if a user enters some other text into the text field, the value property changes — not in the HTML, but in the memory copy of the object model that the browser maintains. Therefore, if a script queries the text field about the content of the value property, the browser yields the current setting of the property — which isn’t the one specified by the HTML if a user changes the text. To gain access to an object’s property, you use the same kind of dot syntax, hierar- chical addressing scheme you saw earlier for objects. A property is contained by its object, so the reference to it consists of the reference to the object plus one more extension naming the property. Therefore, for the button and text object tags just shown, references to various properties are document.formName.clicker.name document.formName.clicker.value document.formName.entry.value Chapter 4 ✦ Browser and Document Objects 53 You may wonder what happened to the window part of the reference. It turns out that there can be only one document contained in a window, so references to objects inside the document can omit the window portion and start the reference with document. You cannot omit the document object, however, from the reference. In IE4+, you can reference an element object by simply referring to the element’s ID attribute if one is assigned. Even so, I strongly recommend spelling out references so that your code is easier to read and understand long after you’ve written it. Notice, too, that the button and text fields both have a property named value. These properties represent very different attributes for each object. For the button, the property determines the button label; for the text field, the property reflects the current text in the field. You now see how the (sometimes lengthy) hierarchical ref- erencing scheme helps the browser locate exactly the object and property your script needs. No two items in a document can have identical references even though parts of these references may have the same component names. Methods If a property is like a descriptive adjective for an object, then a method is a verb. A method is all about action related to the object. A method either does something to the object or with the object that affects other parts of a script or document. They are commands of a sort, but whose behaviors are tied to a particular object. An object can have any number of methods associated with it (including none at all). To set a method into motion (usually called invoking a method), a JavaScript statement must include a reference to it — via its object with a pair of parentheses after the method name — as in the following examples: document.orderForm.submit() document.orderForm.entry.select() The first is a scripted way of clicking a Submit button to send a form (named orderForm) to a server. The second selects the text inside a text field named entry (which is contained by a form named orderForm). Sometimes a method requires that you send additional information with it so that it can do its job. Each chunk of information passed with the method is called a param- eter or argument ( you can use the terms interchangeably). You saw examples of passing a parameter in your first script in Chapter 3. Two script statements invoked the write() method of the document object: document.write(“This browser is version “ + navigator.appVersion) document.write(“ of ” + navigator.appName + “.”) As the page loaded into the browser, each document.write() method sent what- ever text was inside the parentheses to the current document. In both cases, the content being sent as a parameter consisted of straight text (inside quotes) and the values of two object properties: the appVersion and appName properties of the 54 Part II ✦ JavaScript Tutorial navigator object. ( The navigator object does not appear in the object hierarchy diagram of Figure 4-6 because in early browsers this object exists outside of the document object model.) Some methods require more than one parameter. If so, the multiple parameters are separated by commas. For example, version 4 and later browsers support a window object method that moves the window to a particular coordinate point on the screen. A coordinate point is defined by two numbers that indicate the number of pixels from the left and top edges of the screen where the top-left corner of the win- dow should be. To move the browser window to a spot 50 pixels from the left and 100 pixels from the top, the method is window.moveTo(50,100) As you learn more about the details of JavaScript and the document objects you can script, pay close attention to the range of methods defined for each object. They reveal a lot about what an object is capable of doing under script control. Event handlers One last characteristic of a JavaScript object is the event handler. Events are actions that take place in a document, usually as the result of user activity. Common exam- ples of user actions that trigger events include clicking a button or typing a character into a text field. Some events, such as the act of loading a document into the browser window or experiencing a network error while an image loads, are not so obvious. Almost every JavaScript object in a document receives events of one kind or another — summarized for your convenience in the Quick Reference of Appendix A. What determines whether the object does anything in response to the event is an extra attribute you enter into the object’s HTML definition. The attribute consists of the event name, an equal sign ( just like any HTML attribute), followed by instruc- tions about what to do when the particular event fires. Listing 4-1 shows a very sim- ple document that displays a single button with one event handler defined for it. Listing 4-1: A Simple Button with an Event Handler
The form definition contains what, for the most part, looks like a standard input item. But notice the last attribute, onClick=”window.alert(‘Ouch!’)”. Button Chapter 4 ✦ Browser and Document Objects 55 objects, as you see in their complete descriptions in Chapter 24, react to mouse clicks. When a user clicks the button, the browser sends a click event to the button. In this button’s definition, the attribute says that whenever the button receives that message, it should invoke one of the window object’s methods, alert(). The alert() method displays a simple alert dialog box whose content is whatever text is passed as a parameter to the method. Like most arguments to HTML attributes, the attribute setting to the right of the equal sign goes inside quotes. If additional quotes are necessary, as in the case of the text to be passed along with the event handler, those inner quotes can be single quotes. In actuality, JavaScript doesn’t distinguish between single or double quotes but does require that each set be of the same type. Therefore, you can write the attribute this way: onClick=’alert(“Ouch!”)’ Exercises 1. Which of the following applications are well suited to client-side JavaScript? Why or why not? a. Music jukebox b. Web-site visit counter c. Chat room d. Graphical Fahrenheit-to-Celsius temperature calculator e. All of the above f. None of the above 2. General Motors has separate divisions for its automobile brands: Chevrolet, Pontiac, Buick, and Cadillac. Each brand has several models of automobile. Following this hierarchy model, write the dot-syntax equivalent reference to the following three vehicle models: a. Chevrolet Malibu b. Pontiac Firebird c. Pontiac GrandAm 3. Which of the following object names are valid in JavaScript? For each one that is invalid, explain why. a. lastName b. company_name c. 1stLineAddress d. zip code e. today’s_date 56 Part II ✦ JavaScript Tutorial 4. An HTML document contains tags for one link and one form. The form con- tains tags for three text boxes, one checkbox, a Submit button, and a Reset button. Using the object hierarchy diagram from Figure 4-6 for reference, draw a diagram of the object model that the browser would create in its memory for these objects. Give names to the link, form, text fields, and checkbox, and write the references to each of those objects. 5. Write the HTML tag for a button input element named “Hi,” whose visible label reads “Howdy” and whose onClick event handler displays an alert dialog box that says “Hello to you, too!” ✦ ✦ ✦ 55C H A P T E R ✦ ✦ ✦ ✦ In This Chapter Where to place scripts in HTML documents What a JavaScript statement is What makes a script run Viewing script errors ✦ ✦ ✦ ✦ Scripts and HTML Documents In this chapter’s tutorial, you begin to see how scripts are embedded within HTML documents and what comprises a script statement. You also see how script statements can run when the document loads or in response to user action. Finally, you find out where script error information is hiding. Where Scripts Go in Documents Chapter 4 did not thoroughly cover what scripts look like or how you add them to an HTML document. That’s where this lesson picks up the story. The tag set. This is common usage in HTML where start and end tags encapsulate content controlled by that tag, whether the tag set is for a form or a paragraph. Depending on the browser, the If you forget the closing script tag, the script may not run properly and the HTML elsewhere in the page may look strange. Although you don’t work with it in this tutorial, another attribute works with more recent browsers to blend the contents of an external script file into the current doc- ument. An SRC attribute (similar to the SRC attribute of an tag) points to the file containing the script code. Such files must end with a .js extension. The tag set looks like the following: All script lines are in the external file, so no script lines are included between the start and end script tags in the document. Chapter 5 ✦ Scripts and HTML Documents 59 Tag positions Where do these tags go within a document? The answer is, anywhere they’re needed in the document. Sometimes it makes sense to include the tags nested within the ... tag set; other times it is essential that you drop the script into a very specific location in the ... section. In the following four listings, I demonstrate — with the help of a skeletal HTML document — some of the possibilities of On the other hand, if you need a script to run as the page loads so that the script generates content in the page, the script goes in the portion of the docu- ment, as shown in Listing 5-2. If you check the code listing for your first script in Chapter 3, you see that the script tags are in the Body because the script needs to fetch information about the browser and write the results to the page as the page loads. 60 Part II ✦ JavaScript Tutorial Listing 5-2: A Script in the Body A Document It’s also good to know that you can place an unlimited number of You also are not limited to one Handling older browsers Only browsers that include JavaScript in them know to interpret the lines of code between the tag pair as script statements and not HTML text for display in the browser. This means that a pre-JavaScript browser not only ignores the tags, but it also treats the JavaScript code as page content. As you saw at the end of Chapter 3 in an illustration of your first script running on an old browser, the results can be disastrous to a page. You can reduce the risk of old browsers displaying the script lines by playing a trick. The trick is to enclose the script lines between HTML comment symbols, as shown in Listing 5-5. Most nonscriptable browsers completely ignore the content between the comment tags, whereas scriptable browsers ignore those comment symbols when they appear inside a 62 Part II ✦ JavaScript Tutorial The odd construction right before the ending script tag needs a brief explanation. The two forward slashes are a JavaScript comment symbol. This symbol is neces- sary because JavaScript otherwise tries to interpret the components of the ending HTML symbol (-->). Therefore, the forward slashes tell JavaScript to skip the line entirely; a nonscriptable browser simply treats those slash characters as part of the entire HTML comment to be ignored. Despite the fact that this technique is often called hiding scripts, it does not disguise the scripts entirely. All client-side JavaScript scripts are part of the HTML document and download to the browser just like all other HTML. Furthermore, you can view them as part of the document’s source code. Do not be fooled into thinking that you can hide your scripts entirely from prying eyes. JavaScript Statements Virtually every line of code that sits between a tag pair is a JavaScript statement. To be compatible with habits of experienced programmers, JavaScript accepts a semicolon at the end of every statement. Fortunately for new- comers, this semicolon is optional. The carriage return at the end of a statement suffices for JavaScript to know the statement has ended. A statement must be in the script for a purpose. Therefore, every statement does “something” relevant to the script. The kinds of things that statements do are ✦ Define or initialize a variable ✦ Assign a value to a property or variable ✦ Change the value of a property or variable ✦ Invoke an object’s method ✦ Invoke a function routine ✦ Make a decision If you don’t yet know what all of these mean, don’t worry — you will by the end of this tutorial. The point I want to stress is that each statement contributes to the scripts you write. The only statement that doesn’t perform any explicit action is the comment. A pair of forward slashes (no space between them) is the most common way to include a comment in a script. You add comments to a script for your bene- fit. They usually explain in plain language what a statement or group of statements does. The purpose of including comments is to remind you six months from now how your script works. Chapter 5 ✦ Scripts and HTML Documents 63 When Script Statements Execute Now that you know where scripts go in a document, it’s time to look at when they run. Depending on what you need a script to do, you have four choices for deter- mining when a script runs: ✦ While a document loads ✦ Immediately after a document loads ✦ In response to user action ✦ When called upon by other script statements The determining factor is how the script statements are positioned in a document. While a document loads — immediate execution Your first script in Chapter 3 (reproduced in Listing 5-6) runs while the document loads into the browser. For this application, it is essential that a script inspects some properties of the navigator object and includes those property values in the content being rendered for the page as it loads. It makes sense, therefore, to include the 64 Part II ✦ JavaScript Tutorial Deferred scripts The other three ways that script statements run are grouped together as what I called deferred scripts. To demonstrate these deferred script situations, I must intro- duce you briefly to a concept covered in more depth in Chapter 7: the function. A function defines a block of script statements summoned to run some time after those statements load into the browser. Functions are clearly visible inside a Here is some body text. Chapter 5 ✦ Scripts and HTML Documents 65 Don’t worry about the curly braces or other oddities in Listing 5-7 that cause you concern at this point. Focus instead on the structure of the document and the flow. The entire page loads without running any script statements, although the page loads the done() function in memory so that it is ready to run at a moment’s notice. After the document loads, the browser fires the onLoad event handler, which causes the done() function to run. Then the user sees the alert dialog box. Getting a script to execute in response to a user action is very similar to the preceding example for running a deferred script right after the document loads. Commonly, a script function is defined in the Head portion, and an event handler in, say, a form element calls upon that function to run. Listing 5-8 includes a script that runs when a user clicks a button. Listing 5-8: Running a Script from User Action An onClick script Here is some body text.
Not every object must have an event handler defined for it in the HTML, as shown in Listing 5-8 — only the ones for which scripting is needed. No script statements execute in Listing 5-8 until the user clicks the button. The alertUser() function is defined as the page loads, and it waits to run as long as the page remains loaded in the browser. If it is never called upon to run, there’s no harm done. The last scenario for when script statements run also involves functions. In this case, a function is called upon to run by another script statement. Before you see how that works, it helps to read through the next lesson (Chapter 6). Therefore, I will hold off on this example until later in the tutorial. 66 Part II ✦ JavaScript Tutorial Viewing Script Errors In the early days of JavaScript in browsers, script errors displayed themselves in very obvious dialog boxes. These boxes were certainly helpful for scripters who wanted to debug their scripts. However, if a bug got through to a page served up to a non-technical user, the error alert dialog boxes were not only disruptive, but also scary. To prevent such dialog boxes from disturbing unsuspecting users, the browser makers tried to diminish the visual impact of errors in the browser win- dow. Unfortunately for scripters, it is often easy to overlook the fact that your script contains an error because the error is not so obvious. Recent versions of IE and NN have different ways of letting scripters see the errors. In IE5+, you can set its preferences so that scripts do not generate error dialog boxes (got to Tools ➪ Internet Options ➪ Advanced ➪ Browsing and find the check- box entry that says “Display a notification about every script error”). Even with error dialog boxes turned off, error indications are displayed subtly at the left edge of the browser window’s status bar. An alert icon and message (“Error on page.”) appear in the status bar. If you double-click the icon, the error dialog box appears (see Figure 5-1). Be sure to expand the dialog box by clicking the Show Details but- ton. Unless you turn on script error dialog boxes and keep them coming, you have to train yourself to monitor the status bar when a page loads and after each script runs. Figure 5-1: The expanded IE error dialog box For NN 4.07 and later, the status bar is also your first indication of a script error. A message appears in the status bar that instructs you to go to the location javascript: to see the error details. Viewing the details of the error requires dif- ferent steps, depending on the Navigator version. For NN 4.07 and all subsequent 4.x versions, choose File ➪ Open and enter javascript: For NN6, choose Tasks ➪ Tools ➪ JavaScript Console. The JavaScript console win- dow (a separate window from the Java console) opens to reveal the error message Chapter 5 ✦ Scripts and HTML Documents 67 details (see Figure 5-2). You can keep this window open all the time if you like. Unless you clear the window, subsequent error messages are appended to the bot- tom of the window. Figure 5-2: The NN6 JavaScript Console window Understanding error messages and doing something about them is a very large sub- ject, reserved for advanced discussion in Chapter 45. During this tutorial, however, you can use the error messages to see if you have perhaps mistyped a script from a listing in the book. Scripting versus Programming You may get the impression that scripting is easier than programming. “Scripting” simply sounds easier or more friendly than “programming.” In many respects, this is true. One of my favorite analogies is the difference between a hobbyist who builds model airplanes from scratch and a hobbyist who builds model airplanes from commercial kits. The “from scratch” hobbyist carefully cuts and shapes each piece of wood and metal according to very detailed plans before the model starts to take shape. The commercial kit builder starts with many prefabricated parts and 68 Part II ✦ JavaScript Tutorial assembles them into the finished product. When both builders are finished, you may not be able to tell which airplane was built from scratch and which one came out of a box of components. In the end, both builders used many of the same tech- niques to complete the assembly, and each can take pride in the result. As you’ve seen with the document object model, the browser gives scripters many prefabricated components with which to work. Without the browser, you’d have to be a pretty good programmer to develop from scratch your own application that served up content and offered user interaction. In the end, both authors have work- ing applications that look equally professional. Beyond the document object model, however, “real programming” nibbles its way into the scripting world. That’s because scripts (and programs) work with more than just objects. When I said earlier in this lesson that each statement of a JavaScript script does something, that “something” involves data of some kind. Data is the information associated with objects or other pieces of information that a script pushes around from place to place with each statement. Data takes many forms. In JavaScript, the common incarnations of data are num- bers; text (called strings); objects ( both from the object model and others you can create with scripts); and true and false (called Boolean values). Each programming or scripting language determines numerous structures and lim- its for each kind of data. Fortunately for newcomers to JavaScript, the universe of knowledge necessary for working with data is smaller than in a language such as Java. At the same time, what you learn about data in JavaScript is immediately applicable to future learning you may undertake in any other programming lan- guage — don’t believe for an instant that your efforts in learning scripting will be wasted. Because deep down scripting is programming, you need to have a basic knowledge of fundamental programming concepts to consider yourself a good JavaScript scripter. In the next two lessons, I set aside most discussion about the document object model and focus on the programming principles that will serve you well in JavaScript and future programming endeavors. Exercises 1. Write the complete script tag set for a script whose lone statement is document.write(“Hello, world.”) 2. Build an HTML document and include the answer to the previous question such that the page executes the script as it loads. Open the document in your browser. Chapter 5 ✦ Scripts and HTML Documents 69 3. Add a comment to the script in the previous answer that explains what the script does. 4. Create an HTML document that displays an alert dialog box immediately after the page loads and displays a different alert dialog box when the user clicks a form button. 5. Carefully study the document in Listing 5-9. Without entering and loading the document, predict a. What the page looks like b. How users interact with the page c. What the script does Then type the listing into a text editor as shown (observe all capitalization and punctuation). Do not type a carriage return after the “=” sign in the upperMe function statement; let the line word-wrap as it does in the follow- ing listing. It’s okay to use a carriage return between attribute name/value pairs, as shown in the first tag. Save the document as an HTML file, and load the file into your browser to see how well you did. Listing 5-9: How Does This Page Work? Text Object Value Enter lowercase letters for conversion to uppercase:

✦ ✦ ✦ 66C H A P T E R ✦ ✦ ✦ ✦ In This Chapter What variables are and how to use them Why you must learn how to evaluate expressions How to convert data from one type to another How to use basic operators ✦ ✦ ✦ ✦ Programming Fundamentals, Part I The tutorial breaks away from HTML and documents for a while as you begin to learn programming fundamentals that apply to practically every scripting and programming lan- guage you will encounter. Here, you start learning about vari- ables, expressions, data types, and operators — things that might sound scary if you haven’t programmed before. Don’t worry. With a little practice, you will become quite comfort- able with these terms and concepts. What Language Is This? The language you’re studying is called JavaScript. But the lan- guage has some other names that you may have heard. JScript is Microsoft’s name for the language. By leaving out the “ava,” the company doesn’t have to license the “Java” name from its trademark owner: Sun Microsystems. A standards body called ECMA ( pronounced ECK-ma) now governs the specifications for the language (no matter what you call it). The document that provides all of the details about the language is known as ECMA-262 (it’s the 262nd stan- dard published by ECMA). Both JavaScript and JScript are ECMA-262 compatible. Some earlier browser versions exhibit very slight deviations from ECMA-262 (which came later than the earliest browsers). The most serious discrepancies are noted in the core language reference in Part IV of this book. 72 Part II ✦ JavaScript Tutorial Working with Information With rare exception, every JavaScript statement you write does something with a hunk of information — data. Data may be text information displayed on the screen by a JavaScript statement or the on/off setting of a radio button in a form. Each sin- gle piece of information in programming is also called a value. Outside of program- ming, the term value usually connotes a number of some kind; in the programming world, however, the term is not as restrictive. A string of letters is a value. A num- ber is a value. The setting of a check box (whether it is checked or not) is a value. In JavaScript, a value can be one of several types. Table 6-1 lists JavaScript’s formal data types, with examples of the values you will see displayed from time to time. Table 6-1 JavaScript Value (Data) Types Example Description “Howdy” A series of characters inside quote marks 4.5 true null Any number not inside quote marks A logical true or false Completely devoid of any value A software “thing” that is defined by its properties and methods (arrays are also objects) A function definition Type String Number Boolean Null Object Function A language that contains these few data types simplifies programming tasks, espe- cially those involving what other languages consider to be incompatible types of numbers (integers versus real or floating-point values). In some definitions of syn- tax and parts of objects later in this book, I make specific reference to the type of value accepted in placeholders. When a string is required, any text inside a set of quotes suffices. You will encounter situations, however, in which the value type may get in the way of a smooth script step. For example, if a user enters a number into a form’s text input field, the browser stores that number as a string value type. If the script is to perform some arithmetic on that number, you must convert the string to a number before you can apply the value to any math operations. You see examples of this later in this lesson. Chapter 6 ✦ Programming Fundamentals, Part I 73 Variables Cooking up a dish according to a recipe in the kitchen has one advantage over cooking up some data in a program. In the kitchen, you follow recipe steps and work with real things: carrots, milk, or a salmon fillet. A computer, on the other hand, follows a list of instructions to work with data. Even if the data represents something that looks real, such as the text entered into a form’s input field, once the value gets into the program, you can no longer reach out and touch it. In truth, the data that a program works with is merely a collection of bits (on and off states) in your computer’s memory. More specifically, data in a JavaScript- enhanced Web page occupies parts of the computer’s memory set aside for exclu- sive use by the browser software. In the olden days, programmers had to know the numeric address in memory ( RAM ) where a value was stored to retrieve a copy of it for, say, some addition. Although the innards of a program have that level of com- plexity, programming languages such as JavaScript shield you from it. The most convenient way to work with data in a script is to first assign the data to a variable. It’s usually easier to think of a variable as a basket that holds information. How long the variable holds the information depends on a number of factors. But the instant a Web page clears the window (or frame), any variables it knows about are immediately discarded. Creating a variable You have a couple of ways to create a variable in JavaScript, but one covers you properly in all cases. Use the var keyword, followed by the name you want to give that variable. Therefore, to declare a new variable called myAge, the JavaScript statement is var myAge That statement lets the browser know that you can use that variable later to hold information or to modify any of the data in that variable. To assign a value to a variable, use one of the assignment operators. The most com- mon one by far is the equal sign. If I want to assign a value to the myAge variable at the same time I declare it (a combined process known as initializing the variable), I use that operator in the same statement as the var keyword: var myAge = 45 On the other hand, if I declare a variable in one statement and later want to assign a value to it, the sequence of statements is var myAge myAge = 45 74 Part II ✦ JavaScript Tutorial Use the var keyword only for declaration or initialization — once for the life of any variable name in a document. A JavaScript variable can hold any value type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration what type of value the vari- able will hold. In fact, the value type of a variable can change during the execution of a program. ( This flexibility drives experienced programmers crazy because they’re accustomed to assigning both a data type and a value to a variable.) Variable names Choose the names you assign to variables with care. You’ll often find scripts that use vague variable names, such as single letters. Other than a few specific times where using letters is a common practice (for example, using i as a counting vari- able in repeat loops in Chapter 7), I recommend using names that truly describe a variable’s contents. This practice can help you follow the state of your data through a long series of statements or jumps, especially for complex scripts. A number of restrictions help instill good practice in assigning names. First, you cannot use any reserved keyword as a variable name. That includes all keywords currently used by the language and all others held in reserve for future versions of JavaScript. The designers of JavaScript, however, cannot foresee every keyword that the language may need in the future. By using the kind of single words that cur- rently appear in the list of reserved keywords (see Appendix B), you always run a risk of a future conflict. To complicate matters, a variable name cannot contain space characters. Therefore, one-word variable names are fine. Should your description really benefit from more than one word, you can use one of two conventions to join multiple words as one. One convention is to place an underscore character between the words; the other is to start the combination word with a lowercase letter and capitalize the first letter of each subsequent word within the name — I refer to this as the interCap format. Both of the following examples are valid variable names: my_age myAge My preference is for the second version. I find it easier to type as I write JavaScript code and easier to read later. In fact, because of the potential conflict with future keywords, using multiword combinations for variable names is a good idea. Multiword combinations are less likely to appear in the reserved word list. Variable names have a couple of other important restrictions. Avoid all punctuation symbols except for the underscore character. Also, the first character of a variable name cannot be a numeral. If these restrictions sound familiar, it’s because they’re identical to those for HTML element identifiers described in Chapter 5. Chapter 6 ✦ Programming Fundamentals, Part I 75 Expressions and Evaluation Another concept closely related to the value and variable is expression evaluation — perhaps the most important concept of learning how to program a computer. We use expressions in our everyday language. Remember the theme song of The Beverly Hillbillies? Then one day he was shootin’ at some food And up through the ground came a-bubblin’ crude Oil that is. Black gold. Texas tea. At the end of the song, you find four quite different references (“crude,” “oil,” “black gold,” and “Texas tea”). They all mean oil. They’re all expressions for oil. Say any one of them and other people know what you mean. In our minds, we evaluate those expressions to mean one thing: oil. In programming, a variable always evaluates to its contents, or value. For example, after assigning a value to a variable, such as var myAge = 45 anytime the variable is used in a statement, its value (45) is automatically applied to whatever operation that statement calls. Therefore, if you’re 15 years my junior, I can assign a value to a variable representing your age based on the evaluated value of myAge: var yourAge = myAge - 15 The variable, yourAge, evaluates to 30 the next time the script uses it. If the myAge value changes later in the script, the change has no link to the yourAge variable because myAge evaluated to 45 when it was used to assign a value to yourAge. Expressions in script1.htm You probably didn’t recognize it at the time, but you saw how expression evaluation came in handy in your first script of Chapter 3. Recall the second document.write() statement: document.write(“ of “ + navigator.appName + “.”) 76 Part II ✦ JavaScript Tutorial Testing Evaluation in Navigator You can begin experimenting with the way JavaScript evaluates expressions with the help of The Evaluator Jr. (seen in the following figure), an HTML page you can find on the com- panion CD-ROM. (I introduce the Senior version in Chapter 13.) Enter any JavaScript expres- sion into the top text box, and either press Enter/Return or click the Evaluate button. The Evaluator Jr. for testing expression evaluation The Evaluator Jr. has 26 variables (lowercase a through z) predefined for you. Therefore, you can assign values to variables, test comparison operators, and even do math here. Using the age variable examples from earlier in this chapter, type each of the following statements into the upper text box and observe how each expression evaluates in the Results field. Be sure to observe case-sensitivity in your entries. a = 45 a b = a - 15 b a - b a > b To start over, click the Refresh/Reload button. Chapter 6 ✦ Programming Fundamentals, Part I 77 The document.write() method (remember, JavaScript uses the term method to mean command) requires a parameter in parentheses: the text string to be dis- played on the Web page. The parameter here consists of one expression that joins three distinct strings: “ of “ navigator.appName “.” The plus symbol is one of JavaScript’s ways of joining strings. Before JavaScript can display this line, it must perform some quick evaluations. The first evaluation is the value of the navigator.appName property. This property evaluates to a string of the name of your browser. With that expression safely evaluated to a string, JavaScript can finish the job of joining the three strings in the final evaluation. That evaluated string expression is what ultimately appears on the Web page. Expressions and variables As one more demonstration of the flexibility that expression evaluation offers, this section shows you a slightly different route to the document.write() statement. Rather than join those strings as the direct parameter to the document.write() method, I can gather the strings in a variable and then apply the variable to the document.write() method. Here’s how that method looks, as I simultaneously declare a new variable and assign it a value: var textToWrite = “ of “ + navigator.appName + “.” document.write(textToWrite) This method works because the variable, textToWrite, evaluates to the combined string. The document.write() method accepts that string value and does its dis- play job. As you read a script or try to work through a bug, pay special attention to how each expression (variable, statement, object property) evaluates. I guarantee that as you learn JavaScript (or any language), you will end up scratching your head from time to time because you haven’t stopped to examine how expressions evaluate when a particular kind of value is required in a script. Data Type Conversions I mentioned earlier that the type of data in an expression can trip up some script operations if the expected components of the operation are not of the right type. JavaScript tries its best to perform internal conversions to head off such problems, but JavaScript cannot read your mind. If your intentions differ from the way JavaScript treats the values, you won’t get the results you expect. 78 Part II ✦ JavaScript Tutorial A case in point is adding numbers that may be in the form of text strings. In a sim- ple arithmetic statement that adds two numbers together, you get the expected result: 3 + 3 // result = 6 But if one of those numbers is a string, JavaScript leans toward converting the other value to a string — thus turning the plus sign’s action from arithmetic addi- tion to joining strings. Therefore, in the statement 3 + “3” // result = “33” the “string-ness” of the second value prevails over the entire operation. The first value is automatically converted to a string, and the result joins the two strings. Try this yourself in The Evaluator Jr. If I take this progression one step further, look what happens when another number is added to the statement: 3 + 3 + “3” // result = “63” This might seem totally illogical, but there is logic behind this result. The expres- sion is evaluated from left to right. The first plus operation works on two numbers, yielding a value of 6. But as the 6 is about to be added to the “3,” JavaScript lets the “string-ness” of the “3” rule. The 6 is converted to a string, and two string values are joined to yield “63.” Most of your concern about data types will focus on performing math operations like the ones here. However, some object methods also require one or more param- eters of particular data types. While JavaScript provides numerous ways to convert data from one type to another, it is appropriate at this stage of the tutorial to intro- duce you to the two most common data conversions: string to number and number to string. Converting strings to numbers As you saw in the last section, if a numeric value is stored as a string — as it is when entered into a form text field — your scripts will have difficulty applying that value to a math operation. The JavaScript language provides two built-in functions to con- vert string representations of numbers to true numbers: parseInt() and parseFloat(). There is a difference between integers and floating-point numbers in JavaScript. Integers are always whole numbers, with no decimal point or numbers to the right of a decimal. Floating-point numbers, on the other hand, can have fractional values Chapter 6 ✦ Programming Fundamentals, Part I 79 to the right of the decimal. By and large, JavaScript math operations don’t differen- tiate between integers and floating-point numbers: A number is a number. The only time you need to be cognizant of the difference is when a method parameter requires an integer because it can’t handle fractional values. For example, parame- ters to the scroll() method of a window require integer values of the number of pixels vertically and horizontally you want to scroll the window. That’s because you can’t scroll a window a fraction of a pixel on the screen. To use either of these conversion functions, insert the string value you wish to con- vert as a parameter to the function. For example, look at the results of two different string values when passed through the parseInt() function: parseInt(“42”) // result = 42 parseInt(“42.33”) // result = 42 Even though the second expression passes the string version of a floating-point number to the function, the value returned by the function is an integer. No round- ing of the value occurs here (although other math functions can help with that if necessary). The decimal and everything to its right are simply stripped off. The parseFloat() function returns an integer if it can; otherwise, it returns a float- ing-point number as follows: parseFloat(“42”) // result = 42 parseFloat(“42.33”) // result = 42.33 Because these two conversion functions evaluate to their results, you simply insert the entire function wherever you need a string value converted to a string. Therefore, modifying an earlier example in which one of three values was a string, the complete expression can evaluate to the desired result: 3 + 3 + parseInt(“3”) // result = 9 Converting numbers to strings You’ll have less need for converting a number to its string equivalent than the other way around. As you saw in the previous section, JavaScript gravitates toward strings when faced with an expression containing mixed data types. Even so, it is good practice to perform data type conversions explicitly in your code to prevent any potential ambiguity. The simplest way to convert a number to a string is to take advantage of JavaScript’s string tendencies in addition operations. By adding an empty string to a number, you convert the number to its string equivalent: (“” + 2500) // result = “2500” (“” + 2500).length // result = 4 80 Part II ✦ JavaScript Tutorial In the second example, you can see the power of expression evaluation at work. The parentheses force the conversion of the number to a string. A string is a JavaScript object that has properties associated with it. One of those properties is the length property, which evaluates to the number of characters in the string. Therefore, the length of the string “2500” is 4. Note that the length value is a num- ber, not a string. Operators You will use lots of operators in expressions. Earlier, you used the equal sign (=) as an assignment operator to assign a value to a variable. In the preceding examples with strings, you used the plus symbol (+) to join two strings. An operator generally performs some kind of calculation (operation) or comparison with two values (the value on each side of an operator is called an operand) to reach a third value. In this lesson, I briefly describe two categories of operators — arithmetic and comparison. Chapter 40 covers many more operators, but once you understand the basics here, the others are easier to grasp. Arithmetic operators It may seem odd to talk about text strings in the context of “arithmetic” operators, but you have already seen the special case of the plus (+) operator when one or more of the operands is a string. The plus operator instructs JavaScript to concate- nate ( pronounced kon-KAT-en-eight), or join, two strings together precisely where you place the operator. The string concatenation operator doesn’t know about words and spaces, so the programmer must make sure that any two strings to be joined have the proper word spacing as part of the strings — even if that means adding a space: firstName = “John” lastName = “Doe” fullName = firstName + “ “ + lastName JavaScript uses the same plus operator for arithmetic addition. When both operands are numbers, JavaScript knows to treat the expression as an arithmetic addition rather than a string concatenation. The standard math operators for addition, subtraction, multiplication, and division (+, -, *, /) are built into JavaScript. Comparison operators Another category of operator helps you compare values in scripts — whether two values are the same, for example. These kinds of comparisons return a value of the Boolean type — true or false. Table 6-2 lists the comparison operators. The oper- ator that tests whether two items are equal consists of a pair of equal signs to dis- tinguish it from the single equal sign assignment operator. Chapter 6 ✦ Programming Fundamentals, Part I 81 Table 6-2 JavaScript Comparison Operators Symbol Description == != > >= < <= Equals Does not equal Is greater than Is greater than or equal to Is less than Is less than or equal to Where comparison operators come into greatest play is in the construction of scripts that make decisions as they run. A cook does this in the kitchen all the time: If the sauce is too watery, add a bit of flour. You see comparison operators in action in the next chapter. Exercises 1. Which of the following are valid variable declarations or initializations? Explain why each one is or is not valid. If an item is invalid, how do you fix it so that it is? a. my_name = “Cindy” b. var how many = 25 c. var zipCode = document.form1.zip.value d. var 1address = document.nameForm.address1.value 2. For each of the statements in the following sequence, write down how the someVal expression evaluates after the statement executes in JavaScript. var someVal = 2 someVal = someVal + 2 someVal = someVal * 10 someVal = someVal + “20” someVal = “Robert” 3. Name the two JavaScript functions that convert strings to numbers. How do you give the function a string value to convert to a number? 82 Part II ✦ JavaScript Tutorial 4. Type and load the HTML page and script shown in Listing 6-1. Enter a three- digit number into the top two fields and click the Add button. Examine the code and explain what is wrong with the script. How do you fix the script so the proper sum is displayed in the output field? Listing 6-1: What’s Wrong with This Page? Sum Maker

____________


5. What does the term concatenate mean in the context of JavaScript programming? ✦ ✦ ✦ 77C H A P T E R ✦ ✦ ✦ ✦ In This Chapter How control structures make decisions How to define functions Where to initialize variables efficiently What those darned curly braces are all about The basics of data arrays ✦ ✦ ✦ ✦ Programming Fundamentals, Part II Your tour of programming fundamentals continues in this chapter with subjects that have more intriguing possi- bilities. For example, I show you how programs make deci- sions and why a program must sometimes repeat statements over and over. Before you’re finished here, you will learn how to use one of the most powerful information holders in the JavaScript language: the array. Decisions and Loops Every waking hour of every day you make decisions of some kind — most of the time you probably don’t even realize it. Don’t think so? Well, look at the number of decisions you make at the grocery store, from the moment you enter the store to the moment you clear the checkout aisle. No sooner do you enter the store than you are faced with a decision. Based on the number and size of items you intend to buy, do you pick up a hand-carried basket or attempt to extri- cate a shopping cart from the metallic conga line near the front of the store? That key decision may have impact later when you see a special offer on an item that is too heavy to put into the hand basket. Next, you head for the food aisles. Before entering an aisle, you compare the range of goods stocked in that aisle against items on your shopping list. If an item you need is likely to be found in this aisle, you turn into the aisle and start looking for the item; otherwise, you skip the aisle and move to the head of the next aisle. 84 Part II ✦ JavaScript Tutorial Later, you reach the produce section in search of a juicy tomato. Standing in front of the bin of tomatoes, you begin inspecting them one by one — picking one up, feeling its firmness, checking the color, looking for blemishes or signs of pests. You discard one, pick up another, and continue this process until one matches the criteria you set in your mind for an acceptable morsel. Your last stop in the store is the checkout aisle. “Paper or plastic?” the clerk asks. One more decision to make. What you choose impacts how you get the groceries from the car to the kitchen as well as your recycling habits. In your trip to the store, you go through the same kinds of decisions and repetitions that your JavaScript programs also encounter. If you understand these frameworks in real life, you can now look into the JavaScript equivalents and the syntax required to make them work. Control Structures In the vernacular of programming, the kinds of statements that make decisions and loop around to repeat themselves are called control structures. A control structure directs the execution flow through a sequence of script statements based on simple decisions and other factors. An important part of a control structure is the condition. Just as you may travel dif- ferent routes to work depending on certain conditions (for example, nice weather, nighttime, attending a soccer game), so, too, does a program sometimes have to branch to an execution route if a certain condition exists. Each condition is an expression that evaluates to true or false — one of those Boolean data types men- tioned in Chapter 6. The kinds of expressions commonly used for conditions are expressions that include a comparison operator. You do the same in real life: If it is true that the outdoor temperature is less than freezing, then you put on a coat before going outside. In programming, however, the comparisons are strictly com- parisons of number or string values. JavaScript provides several kinds of control structures for different programming situations. Three of the most common control structures you’ll use are if construc- tions, if...else constructions, and for loops. Chapter 39 covers in great detail other common control structures you should know, some of which were introduced only in Navigator 4 and Internet Explorer 4. For this tutorial, however, you need to learn about the three common ones just mentioned. Chapter 7 ✦ Programming Fundamentals, Part II 85 if constructions The simplest program decision is to follow a special branch or path of the program if a certain condition is true. Formal syntax for this construction follows. Items in italics get replaced in a real script with expressions and statements that fit the situation. if (condition) { statement[s] if true } Don’t worry about the curly braces yet. Instead, get a feel for the basic structure. The keyword, if, is a must. In the parentheses goes an expression that evaluates to a Boolean value. This is the condition being tested as the program runs past this point. If the condition evaluates to true, then one or more statements inside the curly braces execute before continuing on with the next statement after the closing brace. If the condition evaluates to false, then the statements inside the curly brace are ignored and processing continues with the next statement after the closing brace. The following example assumes that a variable, myAge, has had its value set earlier in the script (exactly how is not important for this example). The condition expres- sion compares the value myAge against a numeric value of 18. if (myAge < 18) { alert(“Sorry, you cannot vote.”) } The data type of the value inside myAge must be a number so that the proper com- parison (via the < comparison operator) does the right thing. For all instances of myAge less than 18, the nested statement inside the curly braces runs and displays the alert to the user. After the user closes the alert dialog box, the script continues with whatever statement follows the entire if construction. if . . . else constructions Not all program decisions are as simple as the one shown for the if construction. Rather than specifying one detour for a given condition, you might want the pro- gram to follow either of two branches depending on that condition. It is a fine, but important, distinction. In the plain if construction, no special processing is per- formed when the condition evaluates to false. But if processing must follow one of two special paths, you need the if...else construction. The formal syntax defini- tion for an if...else construction is as follows: if (condition) { statement[s] if true } else { statement[s] if false } 86 Part II ✦ JavaScript Tutorial Everything you know about the condition for an if construction applies here. The only difference is the else keyword, which provides an alternate path for execution to follow if the condition evaluates to false. As an example, the following if...else construction determines how many days are in February for a given year. To simplify the demo, the condition simply tests whether the year divides equally by 4. ( True testing for this value includes special treatment of end-of-century dates, but I’m ignoring that for now.) The % operator symbol is called the modulus operator (covered in more detail in Chapter 40). The result of an operation with this operator yields the remainder of division of the two values. If the remainder is zero, then the first value divides evenly by the second. var febDays var theYear = 1993 if (theYear % 4 == 0) { febDays = 29 } else { febDays = 28 } The important point to see from this example is that by the end of the if...else construction, the febDays variable is set to either 28 or 29. No other value is possible. For years evenly divisible by 4, the first nested statement runs. For all other cases, the second statement runs. Processing then picks up with the next statement after the if...else construction. About Repeat Loops Repeat loops in real life generally mean the repetition of a series of steps until some condition is met, thus enabling you to break out of that loop. Such was the case ear- lier in this chapter when you looked through a bushel of tomatoes for the one that came closest to your ideal tomato. The same can be said for driving around the block in a crowded neighborhood until a parking space opens up. A repeat loop lets a script cycle through a sequence of statements until some condi- tion is met. For example, a JavaScript data validation routine might inspect every character that you enter into a form text field to make sure that each one is a number. Or if you have a collection of data stored in a list, the loop can check whether an entered value is in that list. Once that condition is met, the script can then break out of the loop and continue with the next statement after the loop construction. The most common repeat loop construction used in JavaScript is called the for loop. It gets its name from the keyword that begins the construction. A for loop is a Chapter 7 ✦ Programming Fundamentals, Part II 87 powerful device because you can set it up to keep track of the number of times the loop repeats itself. The formal syntax of the for loop is as follows: for ([initial expression]; [condition]; [update expression]) { statement[s] inside loop } The square brackets mean that the item is optional. However, until you get to know the for loop better, I recommend designing your loops to utilize all three items inside the parentheses. The initial expression portion usually sets the starting value of a counter. The condition — the same kind of condition you saw for if construc- tions — defines the condition that forces the loop to stop going around and around. Finally, the update expression is a statement that executes each time all of the state- ments nested inside the construction complete running. A common implementation initializes a counting variable, i, increments the value of i by one each time through the loop, and repeats the loop until the value of i exceeds some maximum value, as in the following: for (var i = startValue; i <= maxValue; i++) { statement[s] inside loop } Placeholders startValue and maxValue represent any numeric values, including explicit numbers or variables holding numbers. In the update expression is an oper- ator you have not seen yet. The ++ operator adds 1 to the value of i each time the update expression runs at the end of the loop. If startValue is 1, the value of i is 1 the first time through the loop, 2 the second time through, and so on. Therefore, if maxValue is 10, the loop repeats itself 10 times (in other words, as long as i is less than or equal to 10). Generally speaking, the statements inside the loop use the value of the counting variable in their execution. Later in this lesson, I show how the variable can play a key role in the statements inside a loop. At the same time, you see how to break out of a loop prematurely and why you may need to do this in a script. Functions In Chapter 5, you saw a preview of the JavaScript function. A function is a definition of a set of deferred actions. Functions are invoked by event handlers or by state- ments elsewhere in the script. Whenever possible, good functions are designed for reuse in other documents. They can become building blocks you use over and over again. 88 Part II ✦ JavaScript Tutorial If you have programmed before, you can see parallels between JavaScript functions and other languages’ subroutines. But unlike some languages that distinguish between procedures (which carry out actions) and functions (which carry out actions and return values), only one classification of routine exists for JavaScript. A function is capable of returning a value to the statement that invoked it, but this is not a requirement. However, when a function does return a value, the calling state- ment treats the function call like any expression — plugging in the returned value right where the function call is made. I will show some examples in a moment. Formal syntax for a function is as follows: function functionName ( [parameter1]...[,parameterN] ) { statement[s] } Names you assign to functions have the same restrictions as names you assign HTML elements and variables. You should devise a name that succinctly describes what the function does. I tend to use multiword names with the interCap (internally capitalized) format that start with a verb because functions are action items, even if they do nothing more than get or set a value. Another practice to keep in mind as you start to create functions is to keep the focus of each function as narrow as possible. It is possible to generate functions that are literally hundreds of lines long. Such functions are usually difficult to main- tain and debug. Chances are that you can divide the long function into smaller, more tightly focused segments. Function parameters In Chapter 5, you saw how an event handler invokes a function by calling the func- tion by name. Any call to a function, including one that comes from another JavaScript statement, works the same way: a set of parentheses follows the function name. You also can define functions so they receive parameter values from the calling statement. Listing 7-1 shows a simple document that has a button whose onClick event handler calls a function while passing text data to the function. The text string in the event handler call is in a nested string — a set of single quotes inside the double quotes required for the entire event handler attribute. Chapter 7 ✦ Programming Fundamentals, Part II 89 Listing 7-1: Calling a Function from an Event Handler
Parameters (also known as arguments) provide a mechanism for “handing off” a value from one statement to another by way of a function call. If no parameters occur in the function definition, both the function definition and call to the function have only empty sets of parentheses (as shown in Chapter 5, Listing 5-8). When a function receives parameters, it assigns the incoming values to the variable names specified in the function definition’s parentheses. Consider the following script segment: function sayHiToFirst(a, b, c) { alert(“Say hello, “ + a) } sayHiToFirst(“Gracie”, “George”, “Harry”) sayHiToFirst(“Larry”, “Moe”, “Curly”) After the function is defined in the script, the next statement calls that very func- tion, passing three strings as parameters. The function definition automatically assigns the strings to variables a, b, and c. Therefore, before the alert() statement inside the function ever runs, a evaluates to “Gracie,” b evaluates to “George,” and c evaluates to “Harry.” In the alert() statement, only the a value is used and the alert reads Say hello, Gracie 90 Part II ✦ JavaScript Tutorial When the user closes the first alert, the next call to the function occurs. This time through, different values are passed to the function and assigned to a, b, and c. The alert dialog box reads Say hello, Larry Unlike other variables that you define in your script, function parameters do not use the var keyword to initialize them. They are automatically initialized whenever the function is called. Variable scope Speaking of variables, it’s time to distinguish between variables that are defined outside and those defined inside of functions. Variables defined outside of functions are called global variables; those defined inside functions are called local variables. A global variable has a slightly different connotation in JavaScript than it has in most other languages. For a JavaScript script, the “globe” of a global variable is the current document loaded in a browser window or frame. Therefore, when you ini- tialize a variable as a global variable, it means that all script statements in the page (including those inside functions) have direct access to that variable value. Statements can retrieve and modify global variables from anywhere in the page. In programming terminology, this kind of variable is said to have global scope because everything on the page can “see” it. It is important to remember that the instant a page unloads itself, all global vari- ables defined in that page are erased from memory. If you need a value to persist from one page to another, you must use other techniques to store that value (for example, as a global variable in a framesetting document, as described in Chapter 16; or in a cookie, as described in Chapter 18). While the var keyword is usually optional for initializing global variables, I strongly recommend you use it for all vari- able initializations to guard against future changes to the JavaScript language. In contrast to the global variable, a local variable is defined inside a function. You already saw how parameter variables are defined inside functions (without var key- word initializations). But you can also define other variables with the var keyword (absolutely required for local variables). The scope of a local variable is only within the statements of the function. No other functions or statements outside of func- tions have access to a local variable. Local scope allows for the reuse of variable names within a document. For most variables, I strongly discourage this practice because it leads to confusion and bugs that are difficult to track down. At the same time, it is convenient to reuse certain kinds of variable names, such as for loop counters. These are safe because they are always reinitialized with a starting value whenever a for loop starts. You can- not, however, nest a for loop inside another without specifying a different loop counting variable. Chapter 7 ✦ Programming Fundamentals, Part II 91 To demonstrate the structure and behavior of global and local variables — and show you why you shouldn’t reuse most variable names inside a document — Listing 7-2 defines two global and two local variables. I intentionally use bad form by initializing a local variable that has the same name as a global variable. Listing 7-2: Global and Local Variable Scope Demonstration When the page loads, the script in the Head portion initializes the two global vari- ables (aBoy and hisDog) and defines the demo() function in memory. In the Body, another script begins by invoking the function. Inside the function, a local variable is initialized with the same name as one of the global variables — hisDog. In JavaScript, such a local initialization overrides the global variable for all statements inside the function. ( But note that if the var keyword is left off of the local initializa- tion, the statement reassigns the value of the global version to “Gromit.”) Another local variable, output, is merely a repository for accumulating the text that is to be written to the screen. The accumulation begins by evaluating the local version of the hisDog variable. Then it concatenates some hard-wired text (note the extra spaces at the edges of the string segment). Next comes the evaluated value of the aBoy global variable — any global not overridden by a local is available for use inside the function. The expression is accumulating HTML to be written to the page, so it ends with a period and a
tag. The final statement of the func- tion writes the content to the page. 92 Part II ✦ JavaScript Tutorial After the function completes its task, the next statement in the Body script writes another string to the page. Because this script statement is executing in global space (that is, not inside any function), it accesses only global variables — includ- ing those defined in another
Window Properties and Methods The one property and three methods for the window object described in this sec- tion have an immediate impact on user interaction. They work with all scriptable browsers. You can find extensive code examples in Part III for each property and method. You can also experiment with the one-statement script examples by entering them in the top text box of The Evaluator Jr. (from Chapter 7). 104 Part II ✦ JavaScript Tutorial window.status property The status bar at the bottom of the browser window normally displays the URL of a link when you roll the mouse pointer atop it. Other messages also appear in that space during document loading, Java applet initialization, and the like. However, you can use JavaScript to display your own messages in the status bar at times that may be beneficial to your users. For example, rather than display the URL of a link, you can display a friendlier, plain-language description of the page at the other end of the link (or a combination of both to accommodate both newbies and geeks). You can assign the window.status property some other text at any time. To change the status bar text of a link as the cursor hovers atop the link, you trigger the action with an onMouseOver event handler of a link object. A peculiarity of the onMouseOver event handler for setting the status bar is that an additional statement — return true — must be part of the event handler. This is very rare in JavaScript, but it is required here for your script to successfully override the status bar. Due to the simplicity of setting the window.status property, it is most common for the script statements to run as inline scripts in the event handler definition. This is handy for short scripts because you don’t have to specify a separate function or add
In Listing 8-3, the situation is a bit more complex because the script generates a subwindow to which is written an entirely script-generated document. To keep the reference to the new window alive across both functions, the newWindow variable is declared as a global variable. As soon as the page loads, the onLoad event handler invokes the makeNewWindow() function. This function generates a blank subwin- dow. I added a property to the third parameter of the window.open() method that instructs the status bar of the subwindow to appear. Chapter 8 ✦ Window and Document Objects 111 A button in the page invokes the subWrite() method. The first task it performs is to check the closed property of the subwindow. This property (which exists only in newer browser versions) returns true if the referenced window is closed. If that’s the case (if the user manually closed the window), the function invokes the makeNewWindow() function again to reopen that window. With the window open, new content is assembled as a string variable. As with Listing 8-2, the content is written in one blast (although that isn’t necessary for a separate window), followed by a close() method. But notice an important differ- ence: both the write() and close() methods explicitly specify the subwindow. Listing 8-3: Using document.write() on Another Window Writing to Subwindow
112 Part II ✦ JavaScript Tutorial The Link Object Belonging to the document object in the hierarchy is the link object. A link object is the object model equivalent of an tag when the tag includes an HREF attribute. A document can have any number of links, so references to links (if necessary) are usually made via the array index method: document.links[n].propertyName More commonly, though, links are not scripted. However, there is an important JavaScript component to these objects. When you want to click a link to execute a script rather than navigate directly to another URL, you can redirect the HREF attribute to call a script function. The technique involves a pseudo-URL called the javascript: URL. If you place the name of a function after the javascript: URL, then a scriptable browser runs that function. So as not to mess with the minds of users, the function should probably perform some navigation in the end. However, the script can do other things as well, such as simultaneously changing the content of two frames within a frameset. The syntax for this construction in a link is as follows: ... The void keyword prevents the link from trying to display any value that the func- tion may return. Remember this javascript: URL technique for all tags that include HREF and SRC attributes: If an attribute accepts a URL, it can accept this javascript: URL as well. This can come in handy as a way to script actions for client-side image maps that don’t necessarily navigate anywhere, but which cause something to happen on the page just the same. The next logical step past the document level in the object hierarchy is the form. That’s where you will spend the next lesson. Exercises 1. Which of the following references are valid and which are not? Explain what is wrong with the invalid references. a. window.document.form[0] b. self.entryForm.entryField.value c. document.forms[2].name d. entryForm.entryField.value e. newWindow.document.write(“Howdy”) Chapter 8 ✦ Window and Document Objects 113 2. Write the JavaScript statement that displays a message in the status bar wel- coming visitors to your Web page. 3. Write the JavaScript statement that displays the same message to the docu- ment as an

-level headline on the page. 4. Create a page that prompts the user for his or her name as the page loads (via a dialog box) and then welcomes the user by name in the body of the page. 5. Create a page with any content you like, but one that automatically displays a dialog box after the page loads to show the user the URL of the current page. ✦ ✦ ✦ 99C H A P T E R ✦ ✦ ✦ ✦ In This Chapter What the FORM object represents How to access key FORM object properties and methods How text, button, and SELECT objects work How to submit forms from a script How to pass information from form elements to functions ✦ ✦ ✦ ✦ Forms and Form Elements Most interactivity between a Web page and the user takes place inside a form. That’s where a lot of the interactive HTML stuff lives for every browser: text fields, but- tons, checkboxes, option lists, and so on. As you can tell from the ( by now) familiar basic object hierarchy diagram (refer back to Figure 8-1), a form is always contained by a document. Even so, the document object must be part of the reference to the form and its elements. The FORM Object A FORM object can be referenced either by its position in the array of forms contained by a document or by name (if you assign an identifier to the NAME attribute inside the
tag). If only one form appears in the document, it is still a member of an array (a one-element array) and is referenced as follows: document.forms[0] Notice that the array reference uses the plural version of the word, followed by a set of square brackets containing the index number of the element (zero is always first). But if you assign a name to the form, simply plug the form’s name into the reference: document.formName Form as object and container In the simplified, compatible object model of this tutorial, a form has a relatively small set of properties, methods, and event handlers. Almost all of the properties are the same as the attributes for forms. All scriptable versions of Navigator, 116 Part II ✦ JavaScript Tutorial and most versions of Internet Explorer, allow scripts to change these properties under script control, which gives your scripts potentially significant power to direct the behavior of a form submission in response to user selections on the page. A form is contained by a document, and the form in turn contains any number of elements (sometimes called form controls). All of those interactive elements that enable users to enter information or make selections belong to the form object. This relationship mirrors the HTML tag organization in which items such as tags are nested between the and
tag “bookends.” Accessing form properties Forms are created entirely from standard HTML tags in the page. You can set attributes for NAME, TARGET, ACTION, METHOD, and ENCTYPE. Each of these is a prop- erty of a FORM object, accessed by all lowercase versions of those words, as in document.forms[0].action document.formName.action To change any of these properties, simply assign new values to them: document.forms[0].action = “http://www.giantco.com/cgi/login.pl” form.elements[ ] property In addition to keeping track of each type of element inside a form, the browser also maintains a list of all control elements within a form. This list is another array, with items listed according to the order in which their HTML tags appear in the source code. It is generally more efficient to create references to elements directly, using their names. However, sometimes a script needs to look through all of the elements in a form. This is especially true if the content of a form changes with each loading of the page because the number of text fields changes based on the user’s browser type. ( For example, a script on the page uses document.write() to add an extra text box for information required only from Windows users.) The following code fragment shows the form.elements[] property at work in a for repeat loop that looks at every element in a form to set the contents of text fields to an empty string. The script cannot simply barge through the form and set every element’s content to an empty string because some elements may be but- tons, which don’t have a value property that you can set to an empty string. var form = window.document.forms[0] for (var i = 0; i < form.elements.length; i++) { if (form.elements[i].type == “text”) { form.elements[i].value = “” } } Chapter 9 ✦ Forms and Form Elements 117 In the first statement, I create a variable — form — that holds a reference to the first form of the document. I do this so that when I make many references to form ele- ments later in the script, the typical length of each reference is much shorter (and marginally faster). I can use the form variable as a shortcut to building references to items more deeply nested in the form. Next, I start looping through the items in the elements array for the form. Each form element has a type property, which reveals what kind of form element it is: text, button, radio, checkbox, and so on. I’m interested in finding elements whose type is text. For each of those, I set the value property to an empty string. I return to forms later in this chapter to show you how to submit a form without a Submit button and how client-side form validation works. Form Controls as Objects Three kinds of HTML elements nested inside a
tag become scriptable objects in all browser document object models. Most of the objects owe their exis- tence to the tag in the page’s source code. Only the value assigned to the TYPE attribute of an tag determines whether the element is a text box, password entry field, hidden field, button, checkbox, or radio button. The other two kinds of form controls, TEXTAREA and SELECT, have their own tags. While form controls have several properties in common, some properties are unique to a particular control type or related types. For example, only a SELECT object offers a property that reveals which item in its list is currently selected. But checkbox and radio buttons both have a property that indicates whether the con- trol is currently set to “on.” Similarly, all text-oriented controls operate the same way for reading and modifying their content. Having a good grasp of the scriptable features of form control objects is important to your success with JavaScript. In the next sections, you meet the most important form control objects and see how scripts interact with them. Text-related objects Each of the four text-related HTML form elements — text, password, hidden, and TEXTAREA — is an element in the document object hierarchy. All but the hidden object display themselves in the page, enabling users to enter information. These objects also display text information that changes in the course of using a page (although Dynamic HTML in IE4+ and NN6+ also allows the scripted change of body text in a document). 118 Part II ✦ JavaScript Tutorial Text Object Behavior Many scripters look to JavaScript to solve what are perceived as shortcomings or behavioral anomalies with text-related objects in forms. I want to single these out early in your scripting experience so that they do not confuse you later. First, only the most recent browsers let scripts reliably alter the font, font size, font style, and text alignment of a text object’s content. You can access changes through the element’s style-related properties (Chapter 30). Second, most browser forms practice a behavior that was recommended long ago as an informal standard by Web pioneers. When a form contains only one text INPUT object, a press of the Enter/Return key while the text object has focus automatically submits the form. For two or more fields in browsers other than IE5/Mac, you need another way to submit the form (for example, a Submit button). This one-field submission scheme works well in many cases, such as the search page of most Web search sites. But if you are experiment- ing with simple forms containing only one field, you can submit the form with a press of the Enter/Return key. Submitting a form that has no other action or target specified means the page performs an unconditional reload — wiping out any information entered into the form. You can, however, cancel the submission through an onSubmit event handler in the form, as shown later in this chapter. Also, starting with version 4 browsers, you can script the press of the Enter/Return key in any text field to submit a form (see Chapter 29). To make these objects scriptable in a page, you do nothing special to their normal HTML tags — with the possible exception of assigning a NAME attribute. I strongly recommend assigning unique names to every form control element if your scripts will be getting or setting properties or invoking their methods. Besides, if the form is actually submitted to a server program, the NAME attributes must be assigned in order for the server to process the element’s data. For the visible objects in this category, event handlers are triggered from many user actions, such as giving a field focus (getting the text insertion pointer in the field) and changing text (entering new text and leaving the field). Most of your text field actions are triggered by the change of text (the onChange event handler). In IE and NN version 4 browsers and later, event handlers fire in response to individual keystrokes as well. Without a doubt, the single most used property of a text-related element is the value property. This property represents the current contents of the text element. A script can retrieve and set its content at any time. Content of the value property is always a string. This may require conversion to numbers (see Chapter 6) if text fields are used to enter values for some math operations. To demonstrate how a text field’s value property can be read and written, Listing 9-1 provides a complete HTML page with a single-entry field. Its onChange event handler invokes the upperMe() function, which converts the text to uppercase. In the upperMe() function, the first statement assigns the text object reference to a Chapter 9 ✦ Forms and Form Elements 119 more convenient variable: field. A lot goes on in the second statement of the func- tion. The right side of the assignment statement performs a couple of key tasks. The reference to the value property of the object (field.value) evaluates to whatever content is in the text field at that instant. That string is then handed over to one of JavaScript’s string functions, toUpperCase(), which converts the value to uppercase. The evaluated result of the right side statement is then assigned to the second variable: upperCaseVersion. Nothing has changed yet in the text box. That comes in the third statement where the value property of the text box is assigned whatever the upperCaseVersion variable holds. The need for the second state- ment is more for learning purposes, so you can see the process more slowly. In practice, you can combine the actions of steps two and three into one power- packed statement: field.value = field.value.toUpperCase() Listing 9-1: Getting and Setting a Text Object’s value Property Text Object value Property
Later in this chapter, I show you how to reduce even further the need for explicit references in functions such as upperMe() in Listing 9-1. In the meantime, notice for a moment the onSubmit event handler in the
tag. I delve more deeply into this event handler later in this chapter, but I want to point out the construction that prevents a single-field form from being submitted when you press the Enter key. The Button Object I have used the button INPUT element in many examples up to this point in the tutorial. The button is one of the simplest objects to script. In the simplified object 120 Part II ✦ JavaScript Tutorial model of this tutorial, the button object has only a few properties that are rarely accessed or modified in day-to-day scripts. Like the text object, the visual aspects of the button are governed not by HTML or scripts, but by the operating system and browser that the page visitor uses. By far, the most useful event handler of the button object is the onClick event handler. It fires whenever the user clicks the button. Simple enough. No magic here. The Checkbox Object A checkbox is also a simple element of the FORM object, but some of the properties may not be intuitive entirely. Unlike the value property of a plain button object (the text of the button label), the value property of a checkbox is any other text you want associated with the object. This text does not appear on the page in any fashion, but the property (initially set via the VALUE tag attribute) might be impor- tant to a script that wants to know more about the purpose of the checkbox within the form. The key property of a checkbox object is whether or not the box is checked. The checked property is a Boolean value: true if the box is checked, false if not. When you see that a property is a Boolean value, it’s a clue that the value might be usable in an if or if...else condition expression. In Listing 9-2, the value of the checked property determines which alert box the user sees. Listing 9-2: The Checkbox Object’s checked Property Checkbox Inspector Check here
Chapter 9 ✦ Forms and Form Elements 121 Checkboxes are generally used as preferences setters, rather than as action inducers. While a checkbox object has an onClick event handler, a click of a check- box should never do anything drastic, such as navigate to another page. The Radio Object Setting up a group of radio objects for scripting requires a bit more work. To let the browser manage the highlighting and unhighlighting of a related group of buttons, you must assign the same name to each of the buttons in the group. You can have multiple groups within a form, but each member of the same group must have the same name. Assigning the same name to a form element forces the browser to manage the ele- ments differently than if they each had a unique name. Instead, the browser main- tains an array list of objects with the same name. The name assigned to the group becomes the name of the array. Some properties apply to the group as a whole; other properties apply to individual buttons within the group and must be addressed via array index references. For example, you can find out how many buttons are in a group by reading the length property of the group: document.forms[0].groupName.length If you want to find out if a particular button is currently highlighted — via the same checked property used for the checkbox — you must access the button element individually: document.forms[0].groupName[0].checked Listing 9-3 demonstrates several aspects of the radio button object, including how to look through a group of buttons to find out which one is checked and how to use the VALUE attribute and corresponding property for meaningful work. The page includes three radio buttons and a plain button. Each radio button’s VALUE attribute contains the full name of one of the Three Stooges. When the user clicks the button, the onClick event handler invokes the fullName() function. In that function, the first statement creates a shortcut reference to the form. Next, a for repeat loop looks through all of the buttons in the stooges radio button group. An if construction looks at the checked property of each button. When a button is highlighted, the break statement bails out of the for loop, leaving the value of the i loop counter at the number where the loop broke ranks. The alert dialog box then uses a reference to the value property of the ith button so that the full name can be displayed in the alert. 122 Part II ✦ JavaScript Tutorial Listing 9-3: Scripting a Group of Radio Objects Extracting Highlighted Radio Button
Select your favorite Stooge: Moe Larry Curly
As you learn about form elements in later chapters of this book, the browser’s ten- dency to create arrays out of identically named objects of the same type (except for Internet Explorer 3) can be a benefit to scripts that work with, say, columns of fields in an HTML order form. The SELECT Object The most complex form element to script is the SELECT element object. As you can see from the lowest common denominator object hierarchy diagram ( Figures 6-1 or 8-4), the SELECT object is really a compound object: an object that contains an array of OPTION objects. Moreover, you can establish this object in HTML to dis- play itself as either a pop-up list or a scrolling list — the latter configurable to accept multiple selections by users. For the sake of simplicity at this stage, this lesson focuses on deployment as a pop-up list that allows only single selections. Chapter 9 ✦ Forms and Form Elements 123 Some properties belong to the entire SELECT object; others belong to individual options inside the SELECT object. If your goal is to determine which item the user selects, you must use properties of both the SELECT and OPTION objects. The most important property of the SELECT object itself is the selectedIndex property, accessed as follows: document.form[0].selectName.selectedIndex This value is the index number of the currently selected item. As with most index counting schemes in JavaScript, the first item (the one at the top of the list) has an index of zero. The selectedIndex value is critical for enabling you to access prop- erties of the selected option. Two important properties of an option item are text and value, accessed as follows: document.forms[0].selectName.options[n].text document.forms[0].selectName.options[n].value The text property is the string that appears onscreen in the SELECT object. It is unusual for this information to be exposed as a FORM object property because in the HTML that generates a SELECT object, the text is defined outside of the