Praise for Danny Goodman’s JavaScript™ Bible “JavaScriptTM Bibleis 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 “JavaScriptTMBibleis 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 fromJavaScriptTMBible. What an amazing book! Danny Goodman is the greatest!” —Patrick Moss “Danny Goodman is very good at leading the reader into the subject. JavaScriptTM Biblehas 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 “JavaScriptTMBibleis by farthe 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 Express Computer Distributors for the Caribbean Published by and West Indies; by Micronesia Media Distributor, Inc. Hungry Minds, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. 909 Third Avenue for Mexico; by Editorial Norma de Panama S.A. for New York, NY 10022 Panama; by American Bookshops for Finland. www.hungryminds.com For general information on Hungry Minds’ products Copyright © 2001 Danny Goodman. All rights and services please contact our Customer Care reserved. No part of this book, including interior department within the U.S. at 800-762-2974, outside design, cover design, and icons, may be reproduced the U.S. at 317-572-3993 or fax 317-572-4002. or transmitted in any form, by any means For sales inquiries and reseller information, (electronic, photocopying, recording, or otherwise) including discounts, premium and bulk quantity without the prior written permission of the sales, and foreign-language translations, please publisher. contact our Customer Care department at Library of Congress Control Number: 200101676 800-434-3422, fax 317-572-4002 or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 ISBN: 0-7645-3342-8 Crosspoint Boulevard, Indianapolis, IN 46256. Printed in the United States of America For information on licensing foreign or domestic 10 9 8 7 6 5 4 3 2 1 rights, please contact our Sub-Rights Customer Care 4B/SR/QT/QR/IN department at 650-653-7098. Distributed in the United States by Hungry Minds, Inc. For information on using Hungry Minds’ products Distributed by CDG Books Canada Inc. for Canada; by and services in the classroom or for ordering Transworld Publishers Limited in the United examination copies, please contact our Educational Kingdom; by IDG Norge Books for Norway; by IDG Sales department at 800-434-2086 or fax 317-572-4005. Sweden Books for Sweden; by IDG Books Australia For press review copies, author interviews, or other Publishing Corporation Pty. Ltd. for Australia and New publicity information, please contact our Public Zealand; by TransQuest Publishers Pte Ltd. for Relations department at 650-653-7000 or fax Singapore, Malaysia, Thailand, Indonesia, and Hong 650-653-7500. Kong; by Gotop Information Inc. for Taiwan; by ICG For authorization to photocopy items for corporate, Muse, Inc. for Japan; by Intersoft for South Africa; by personal, or educational use, please contact Eyrolles for France; by International Thomson Copyright Clearance Center, 222 Rosewood Drive, Publishing for Germany, Austria, and Switzerland; by Danvers, MA 01923, or fax 978-750-4470. 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 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 Goodmanis 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 ViewSourceonline 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 Quality Control Technicians Debra Williams Cauley Laura Albert Valery Bourke Project Editor Joel Draper Neil Romanosky Dwight Ramsey Technical Editor Permissions Editor David Wall Laura Moss Copy Editors Media Development Specialist Jerelind Charles Greg Stephens Victoria Lee O’Malley Media Development Coordinator Proof Editor Marisa Pearman Cordelia Heaney Book Designer Project Coordinator Kurt Krames Regina Snyder Proofreading Graphics and Production Specialists York Production Services Sean Decker LeAndra Johnson Indexer Stephanie Jumper Johnna VanHoose Dinse Barry Offringa Kristin Pickett Cover Illustrator Jill Piscitelli Kate Shaw Jeremey Unger Erin Zeltner 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 Handbookby 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 thegoal 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 Bibleto 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 F or 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) Biblerepresents 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.