30
JavaScript ® Bible Sixth Edition Danny Goodman with Michael Morrison With a foreword by Brendan Eich, JavaScript’s creator

JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

JavaScript® BibleSixth Edition

Danny Goodman with Michael Morrison

With a foreword by Brendan Eich, JavaScript’s creator

01_069165 ffirs.qxp 3/1/07 3:38 PM Page iii

Page 2: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

A major new edition of the definitive guide to JavaScript!Make your Web pages stand out above the noise with JavaScript and the expert instruction in this much-anticipated update to the bestselling JavaScript Bible. With renowned JavaScript expert Danny Goodman at your side, you’ll get a thorough grounding in JavaScript basics, see how it fits with current Web browsers, and find all the soup-to-nuts detail you’ll need, whether you’re a veteran programmer or just starting out. This is the JavaScript book Web developers turn to again and again.

Shelving Category:

COMPUTERS/Internet/Web Site Design

Reader Level:Beginning to Advanced

$49.99 USA $59.99 Canada £31.99 UK

ISBN 978-0-470-06916-5

www.wiley.com/compbooks

• Master JavaScript fundamentals and write your first practical script

• Develop code for both single- and cross-platform audiences and evolving standards

• Get the essentials of document object models and HTML element objects

• Write scripts that dynamically modify Web pages in response to user actions

• Learn the power of new Ajax technologies to create efficient Web page user interfaces

• Apply the latest JavaScript exception handling and custom object techniques

• Create interactivity with sites like Google Maps™

Page 3: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Praise for Danny Goodman’s JavaScript®Bible“JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than three feetfrom 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 advancedWeb sites. Mr. Goodman did an excellent job of organizing this book and writing it so that even a begin-ning 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

“JavaScript® 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 [JavaScript® Bible]. It’s so simple touse—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

“Danny Goodman is very good at leading the reader into the subject. JavaScript® Bible has everything wecould possibly need.”

—Philip Gurdon

“An excellent book that builds solidly from whatever level the reader is at. A book that is both witty andeducational.”

—Dave Vane

“I continue to use the book on a daily basis and would be lost without it.”

—Mike Warner, Founder, Oak Place Productions

“JavaScript® 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

01_069165 ffirs.qxp 3/1/07 3:38 PM Page i

Page 4: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

01_069165 ffirs.qxp 3/1/07 3:38 PM Page ii

Page 5: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

JavaScript® BibleSixth Edition

Danny Goodman with Michael Morrison

With a foreword by Brendan Eich, JavaScript’s creator

01_069165 ffirs.qxp 3/1/07 3:38 PM Page iii

Page 6: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

JavaScript® Bible, Sixth Edition

Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

Copyright © 2007 by Danny Goodman

Published by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-06916-5

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 ofthe 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorizationthrough payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the LegalDepartment, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)572-4355, or online at http://www.wiley.com/go/permissions.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NOREPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THECONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUTLIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OREXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREINMAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THATTHE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONALSERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONALPERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FORDAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THISWORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THATTHE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAYPROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNETWEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORKWAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services or to obtain technical support, please contact our CustomerCare Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.

Library of Congress Cataloging-in-Publication Data

Goodman, Danny.JavaScript bible / Danny Goodman with Michael Morrison ; with a foreword by Brendan Eich. — 6th ed.

p. cm.Includes index.ISBN-13: 978-0-470-06916-5 (paper/cd-rom)ISBN-10: 0-470-06916-3 (paper/cd-rom)1. JavaScript (Computer program language) I. Morrison, Michael, 1970– II. Title. QA76.73.J39G65 2007005.13'3—dc22 2006101137

Trademarks: Wiley, the Wiley logo, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc.and/or its affiliates, in the United States and other countries, and may not be used without written permission. JavaScript is aregistered trademark of Sun Microsystems Inc. in the United States and other countries. All other trademarks are the property oftheir respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available inelectronic books.

01_069165 ffirs.qxp 3/1/07 3:38 PM Page iv

Page 7: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

About the AuthorsDanny Goodman is the author of numerous critically acclaimed and best-selling books, including TheComplete HyperCard Handbook, Danny Goodman’s AppleScript Handbook, Dynamic HTML: The DefinitiveReference, and JavaScript & DHTML Cookbook. He is a renowned authority and expert teacher of computerscripting languages. His writing style and pedagogy continue to earn praise from readers and teachersaround the world. To help keep his finger on the pulse of real-world programming challenges, Goodmanfrequently lends his touch as consulting programmer and designer to leading-edge World Wide Web andintranet sites from his home base in the San Francisco area.

Michael Morrison is a writer, developer, toy inventor, and author of a variety of books covering topics suchas Java, C++, Web scripting, XML, game development, and mobile devices. Some of Michael’s notable writ-ing projects include Faster Smarter HTML and XML, Teach Yourself HTML & CSS in 24 Hours, and BeginningGame Programming. Michael is also the founder of Stalefish Labs (www.stalefishlabs.com), an enter-tainment company specializing in unusual games, toys, and interactive products.

01_069165 ffirs.qxp 3/1/07 3:38 PM Page v

Page 8: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

CreditsAcquisitions EditorKit Kemper

Senior Development EditorKevin Kent

Copy EditorTravis Henderson

Editorial ManagerMary Beth Wakefield

Production ManagerTim Tate

Vice President and Executive GroupPublisherRichard Swadley

Vice President and Executive PublisherJoseph B. Wikert

Project CoordinatorLynsey Osborn

Graphics and Production SpecialistsBrooke GraczykJoyce HaugheyJennifer MayberryAlicia B. South

Quality Control TechniciansDavid FaustJohn Greenough

Media Development Project SupervisorLaura Atkinson

Media Development SpecialistKate Jenkins

ProofreadingDavid FaustKathy SimpsonSossity Smith

IndexingValerie Haynes Perry

Anniversary Logo DesignRichard Pacifico

01_069165 ffirs.qxp 3/1/07 3:38 PM Page vi

Page 9: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

This sixth edition is the second time I’ve been fortunate enough to have Michael Morrison—a first-rate author and scripter in his own right—help bring the content of the book up to date. Whenyou add the hundreds of pages on the CD-ROM to the 1,200+ pages of the printed book, the job

of revising JavaScript Bible is monumental in scale. I therefore appreciate the personal sacrifices Michaelmade while he kept the motor running during extensive revision cycles. Many thanks to the hard-working folks at Wiley Publishing, Kit Kemper and Kevin Kent. Above all, I want to thank the manyreaders of the earlier editions of this book for investing in this ongoing effort. I wish I had the space hereto acknowledge by name so many who have sent e-mail notes and suggestions: Your input has beenmost welcome and greatly appreciated.

vii

01_069165 ffirs.qxp 3/1/07 3:38 PM Page vii

Page 10: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

01_069165 ffirs.qxp 3/1/07 3:38 PM Page viii

Page 11: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

About the Authors ........................................................................................................................vAcknowledgments ......................................................................................................................viiForeword ..................................................................................................................................xviiPreface........................................................................................................................................xix

Part I: Getting Started with JavaScript 1

Chapter 1: JavaScript’s Role in the World Wide Web and Beyond . . . . . . . 3Competing for Web Traffic ............................................................................................................4Other Web Technologies ..............................................................................................................4JavaScript: A Language for All ......................................................................................................6JavaScript: The Right Tool for the Right Job ..................................................................................8

Chapter 2: Authoring Challenges Amid the Browser Wars . . . . . . . . . . . 9Leapfrog ........................................................................................................................................9Duck and Cover ..........................................................................................................................10Compatibility Issues Today..........................................................................................................11Developing a Scripting Strategy ..................................................................................................14

Chapter 3: Your First JavaScript Script . . . . . . . . . . . . . . . . . . . . . 17The Software Tools ......................................................................................................................17Setting Up Your Authoring Environment ....................................................................................18What Your First Script Will Do....................................................................................................21Entering Your First Script ............................................................................................................21Examining the Script ..................................................................................................................23Have Some Fun ..........................................................................................................................25

Part II: JavaScript Tutorial 27

Chapter 4: Browser and Document Objects . . . . . . . . . . . . . . . . . . 29Scripts Run the Show ..................................................................................................................29When to Use JavaScript ..............................................................................................................30The Document Object Model ......................................................................................................31When a Document Loads ............................................................................................................33Object References........................................................................................................................36Node Terminology ......................................................................................................................38What Defines an Object? ............................................................................................................39Exercises ....................................................................................................................................43

ix

02_069165 ftoc.qxp 3/1/07 4:02 PM Page ix

Page 12: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Chapter 5: Scripts and HTML Documents . . . . . . . . . . . . . . . . . . . 45Where Scripts Go in Documents ................................................................................................45JavaScript Statements ..................................................................................................................49When Script Statements Execute ................................................................................................49Viewing Script Errors ..................................................................................................................52Scripting versus Programming ....................................................................................................54Exercises ....................................................................................................................................55

Chapter 6: Programming Fundamentals, Part I. . . . . . . . . . . . . . . . . 57What Language Is This? ..............................................................................................................57Working with Information ..........................................................................................................57Variables......................................................................................................................................58Expressions and Evaluation ........................................................................................................60Data Type Conversions ................................................................................................................62Operators ....................................................................................................................................64Exercises ....................................................................................................................................65

Chapter 7: Programming Fundamentals, Part II . . . . . . . . . . . . . . . . 67Decisions and Loops....................................................................................................................67Control Structures ......................................................................................................................68About Repeat Loops ....................................................................................................................69Functions ....................................................................................................................................70About Curly Braces ....................................................................................................................74Arrays..........................................................................................................................................74Exercises ....................................................................................................................................78

Chapter 8: Window and Document Objects . . . . . . . . . . . . . . . . . . 81Top-Level Objects........................................................................................................................81The window Object ....................................................................................................................82Window Properties and Methods ................................................................................................85The location Object ....................................................................................................................87The navigator Object ..................................................................................................................88The document Object..................................................................................................................88Exercises ....................................................................................................................................93

Chapter 9: Forms and Form Elements. . . . . . . . . . . . . . . . . . . . . . 95The form Object..........................................................................................................................95Form Controls as Objects ............................................................................................................97Passing Form Data and Elements to Functions ..........................................................................104Submitting and Prevalidating Forms..........................................................................................106Exercises ..................................................................................................................................108

Chapter 10: Strings, Math, and Dates . . . . . . . . . . . . . . . . . . . . . 109Core Language Objects..............................................................................................................109String Objects............................................................................................................................110The Math Object ......................................................................................................................113The Date Object ........................................................................................................................114Date Calculations ......................................................................................................................115Exercises ..................................................................................................................................117

x

Contents

02_069165 ftoc.qxp 3/1/07 4:02 PM Page x

Page 13: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Chapter 11: Scripting Frames and Multiple Windows . . . . . . . . . . . . 119Frames: Parents and Children ..................................................................................................119References Among Family Members ..........................................................................................121Frame-Scripting Tips ................................................................................................................123About iframe Elements ..............................................................................................................124Controlling Multiple Frames: Navigation Bars ..........................................................................124References for Multiple Windows..............................................................................................126Exercises ..................................................................................................................................128

Chapter 12: Images and Dynamic HTML . . . . . . . . . . . . . . . . . . . 129The Image Object ......................................................................................................................129Rollovers Without Scripts..........................................................................................................135The javascript: Pseudo-URL ......................................................................................................137Popular Dynamic HTML Techniques ........................................................................................138Exercises ..................................................................................................................................140

Part III: Document Objects Reference 141

Chapter 13: JavaScript Essentials . . . . . . . . . . . . . . . . . . . . . . . 143JavaScript Versions ....................................................................................................................143Core Language Standard: ECMAScript ......................................................................................144Embedding Scripts in HTML Documents ..................................................................................145Browser Version Detection ........................................................................................................149Designing for Compatibility ......................................................................................................154Language Essentials for Experienced Programmers....................................................................158Onward to Object Models ........................................................................................................161

Chapter 14: Document Object Model Essentials . . . . . . . . . . . . . . . 163The Object Model Hierarchy ....................................................................................................163How Document Objects Are Born ............................................................................................166Object Properties ......................................................................................................................166Object Methods ........................................................................................................................167Object Event Handlers ..............................................................................................................168Object Model Smorgasbord ......................................................................................................169Basic Object Model....................................................................................................................169Basic Object Model Plus Images ................................................................................................170Navigator 4–Only Extensions ....................................................................................................170Internet Explorer 4+ Extensions ................................................................................................171Internet Explorer 5+ Extensions ................................................................................................174The W3C DOM ........................................................................................................................175Scripting Trends ........................................................................................................................190Standards Compatibility Modes (DOCTYPE Switching) ............................................................191Where to Go from Here ............................................................................................................192

Chapter 15: Generic HTML Element Objects. . . . . . . . . . . . . . . . . 195Generic Objects ........................................................................................................................196

xi

Contents

02_069165 ftoc.qxp 3/1/07 4:02 PM Page xi

Page 14: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Chapter 16: Window and Frame Objects . . . . . . . . . . . . . . . . . . . 369Window Terminology................................................................................................................369Frames ......................................................................................................................................370window Object..........................................................................................................................376frame Element Object................................................................................................................471frameset Element Object ..........................................................................................................478iframe Element Object ..............................................................................................................484popup Object ............................................................................................................................490

Chapter 17: Location and History Objects . . . . . . . . . . . . . . . . . . 495location Object..........................................................................................................................496history Object ..........................................................................................................................513

Chapter 18: The Document and Body Objects . . . . . . . . . . . . . . . . 519document Object ......................................................................................................................520body Element Object ................................................................................................................587TreeWalker Object ....................................................................................................................595

Chapter 19: Link and Anchor Objects. . . . . . . . . . . . . . . . . . . . . 599Anchor, Link, and a Element Objects ........................................................................................600

Chapter 20: Image, Area, Map, and Canvas Objects . . . . . . . . . . . . . 607Image and img Element Objects ................................................................................................607area Element Object ..................................................................................................................626map Element Object..................................................................................................................630canvas Element Object ..............................................................................................................634

Chapter 21: The Form and Related Objects. . . . . . . . . . . . . . . . . . 645The Form in the Object Hierarchy ............................................................................................645form Object ..............................................................................................................................646fieldset and legend Element Objects ..........................................................................................663label Element Object ................................................................................................................665Scripting and Web Forms 2.0....................................................................................................666

Chapter 21: Button Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 669The button Element Object, and the Button, Submit, and Reset Input Objects..........................669checkbox Input Object..............................................................................................................675radio Input Object ....................................................................................................................682image Input Object ..................................................................................................................688

Chapter 23: Text-Related Form Objects . . . . . . . . . . . . . . . . . . . . 691Text Input Object ......................................................................................................................691password Input Object ..............................................................................................................706hidden Input Object..................................................................................................................707textarea Element Object ............................................................................................................708

Chapter 24: Select, Option, and FileUpload Objects . . . . . . . . . . . . 713select Element Object ................................................................................................................713option Element Object ..............................................................................................................732optgroup Element Object ..........................................................................................................734file Input Element Object ..........................................................................................................736

xii

Contents

02_069165 ftoc.qxp 3/1/07 4:02 PM Page xii

Page 15: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Chapter 25: Event Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 739Why “Events”? ..........................................................................................................................740Event Propagation ....................................................................................................................741Referencing the event object......................................................................................................753Binding Events ..........................................................................................................................754event Object Compatibility........................................................................................................758Dueling Event Models ..............................................................................................................760Event Types ..............................................................................................................................763IE4+ event Object......................................................................................................................766NN6+/Moz/Safari event Object..................................................................................................787

Chapter 26: Style Sheet and Style Objects . . . . . . . . . . . . . . . . . . 811Making Sense of the Object Names ..........................................................................................812Imported Stylesheets ................................................................................................................813Reading Style Properties ............................................................................................................813style Element Object ................................................................................................................814styleSheet Object ......................................................................................................................816cssRule and rule Objects ..........................................................................................................825currentStyle, runtimeStyle, and style Objects ............................................................................828filter Object ..............................................................................................................................854

Chapter 27: Ajax and XML . . . . . . . . . . . . . . . . . . . . . . . . . . . 867Elements and Nodes..................................................................................................................868xml Element Object ..................................................................................................................869XMLHttpRequest Object ..........................................................................................................871

Part IV: JavaScript Core Language Reference 881

Chapter 28: The String Object . . . . . . . . . . . . . . . . . . . . . . . . . 883String and Number Data Types..................................................................................................883String Object ............................................................................................................................886String Utility Functions ............................................................................................................908URL String Encoding and Decoding ..........................................................................................912

Chapter 29: The Math, Number, and Boolean Objects. . . . . . . . . . . . 913Numbers in JavaScript ..............................................................................................................913Math Object ..............................................................................................................................919Number Object ........................................................................................................................922Boolean Object ..........................................................................................................................926

Chapter 30: The Date Object . . . . . . . . . . . . . . . . . . . . . . . . . 927Time Zones and GMT................................................................................................................927The Date Object ........................................................................................................................929Validating Date Entries in Forms ..............................................................................................941

xiii

Contents

02_069165 ftoc.qxp 3/1/07 4:02 PM Page xiii

Page 16: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Chapter 31: The Array Object . . . . . . . . . . . . . . . . . . . . . . . . . 945Structured Data ........................................................................................................................945Creating an Empty Array ..........................................................................................................946Populating an Array ..................................................................................................................947JavaScript Array Creation Enhancements ..................................................................................947Deleting Array Entries ..............................................................................................................948Parallel Arrays ..........................................................................................................................948Multidimensional Arrays ..........................................................................................................951Simulating a Hash Table ............................................................................................................952Array Object Properties ............................................................................................................953Array Object Methods ..............................................................................................................955

Chapter 32: Control Structures and Exception Handling . . . . . . . . . . 969If and If. . .Else Decisions ..........................................................................................................969Conditional Expressions............................................................................................................974Repeat (for) Loops ....................................................................................................................975The while Loop ........................................................................................................................979The do-while Loop....................................................................................................................980Looping through Properties (for-in) ..........................................................................................981The with Statement ..................................................................................................................982Labeled Statements....................................................................................................................983The switch Statement ................................................................................................................985Exception Handling ..................................................................................................................988Using try-catch-finally Constructions ........................................................................................990Throwing Exceptions ................................................................................................................993Error Object ..............................................................................................................................997

Chapter 33: JavaScript Operators . . . . . . . . . . . . . . . . . . . . . . 1001Operator Categories ................................................................................................................1001Comparison Operators ............................................................................................................1002Equality of Disparate Data Types ............................................................................................1003Connubial Operators ..............................................................................................................1005Assignment Operators ............................................................................................................1008Boolean Operators ..................................................................................................................1009Bitwise Operators ....................................................................................................................1013Object Operators ....................................................................................................................1014Miscellaneous Operators ........................................................................................................1018Operator Precedence ..............................................................................................................1020

Chapter 34: Functions and Custom Objects. . . . . . . . . . . . . . . . . 1023Function Object ......................................................................................................................1023Function Application Notes ....................................................................................................1032Creating Your Own Objects with Object-Oriented JavaScript ..................................................1039Object-Oriented Concepts ......................................................................................................1052Object Object ..........................................................................................................................1055

Chapter 35: Global Functions and Statements . . . . . . . . . . . . . . . 1061Functions ................................................................................................................................1062Statements ..............................................................................................................................1070

xiv

Contents

02_069165 ftoc.qxp 3/1/07 4:02 PM Page xiv

Page 17: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Part V: Appendixes 1077

Appendix A: JavaScript and Browser Objects Quick Reference . . . . . . 1079

Appendix B: JavaScript Reserved Words . . . . . . . . . . . . . . . . . . . 1087

Appendix C: Answers to Tutorial Exercises . . . . . . . . . . . . . . . . . 1089Chapter 4 Answers ..................................................................................................................1089Chapter 5 Answers ..................................................................................................................1090Chapter 6 Answers ..................................................................................................................1092Chapter 7 Answers ..................................................................................................................1092Chapter 8 Answers ..................................................................................................................1097Chapter 9 Answers ..................................................................................................................1098Chapter 10 Answers ................................................................................................................1101Chapter 11 Answers ................................................................................................................1103Chapter 12 Answers ................................................................................................................1103

Appendix D: JavaScript and DOM Internet Resources . . . . . . . . . . . 1105Support and Updates for This Book ........................................................................................1105Newsgroups ............................................................................................................................1106FAQs ......................................................................................................................................1106Online Documentation............................................................................................................1107World Wide Web ....................................................................................................................1107

Appendix E: What’s on the CD-ROM . . . . . . . . . . . . . . . . . . . . 1109System Requirements ..............................................................................................................1109Disc Contents..........................................................................................................................1110Troubleshooting ......................................................................................................................1111Customer Care ........................................................................................................................1111

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1113

Part VI: Bonus Chapters On the CD-ROM

Chapter 36: Body Text Objects

Chapter 37: HTML Directive Objects

Chapter 38: Table and List Objects

Chapter 39: The Navigator and Other Environment Objects

Chapter 40: Positioned Objects

Chapter 41: Embedded Objects

Chapter 42: The Regular Expression and RegExp Objects

xv

Contents

02_069165 ftoc.qxp 3/1/07 4:02 PM Page xv

Page 18: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Chapter 43: Data-Entry Validation

Chapter 44: Scripting Java Applets and Plug-Ins

Chapter 45: Debugging Scripts

Chapter 46: Security and Netscape Signed Scripts

Chapter 47: Cross-Browser Dynamic HTML Issues

Chapter 48: Internet Explorer Behaviors

Chapter 49: Application: Tables and Calendars

Chapter 50: Application: A Lookup Table

Chapter 51: Application: A Poor Man’s Order Form

Chapter 52: Application: Outline-Style Table of Contents

Chapter 53: Application: Calculations and Graphics

Chapter 54: Application: Intelligent “Updated” Flags

Chapter 55: Application: Decision Helper

Chapter 56: Application: Cross-Browser DHTML Map Puzzle

Chapter 57: Application: Transforming XML Data

Chapter 58: Application: Creating Custom Google Maps

xvi

Contents

02_069165 ftoc.qxp 3/1/07 4:02 PM Page xvi

Page 19: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

As JavaScript’s creator, I would like to say a few words about where JavaScript has been, where it isgoing, 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 documents. Thismay seem obvious now, but in the spring of 1995 it was novel and more than a little at odds with boththe conventional wisdom (that HTML should describe static document structure only) and the Next BigThing (Java applets, which were hyped as the one true way to enliven and extend web pages). Once Igot past these contentions, JavaScript quickly shaped up along the following lines:

n “Java-lite” syntax. Although the “natural language” syntax of HyperTalk was fresh in mymind after a friend lent me The Complete HyperCard Handbook by some fellow namedGoodman, the Next Big Thing weighed heavier, especially in light of another goal: scriptingJava applets. If the scripting language resembled Java, then those programmers who made thejump from JavaScript to Java would welcome similarities in syntax. But insisting on Java’s classand 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 writing short snippets of code,quickly and without fuss.

n Events for HTML elements. Buttons should have onClick event handlers. Documents loadand unload from windows, so windows should have onLoad and onUnload handlers. Usersand scripts submit forms: thus the onSubmit handler. Although not initially as flexible asHyperCard’s messages (whose handlers inspired the onEvent naming convention), JavaScriptevents let HTML authors take control of user interaction from remote servers and respondquickly to user gestures and browser actions. With the adoption of the W3C DOM Level 2event handling recommendations, JavaScript in modern browsers has fully flexible controlover events.

n Objects without classes. The Self programming language proved the notion of prototype-based inheritance. For JavaScript, I wanted a single prototype per object (for simplicity andefficiency), based by default on the function called using the new operator (for consonancewith Java). To avoid distinguishing constructors from methods from functions, all functionsreceive the object naming them as the property that was called in the parameter. Althoughprototypes didn’t appear until Navigator 3, they were prefigured in Version 2 by quoted textbeing treated as an object (the Strong object prototype, to which users could attach methods).

n Generated HTML. Embedding JavaScript in HTML gave rise to a thought: Let the script speakHTML, as if the emitted text and markup were loaded in place of the script itself. The possibil-ities went beyond automating current or last-modified dates, to computing whole trees oftables where all the repeated structure was rolled up in a scripted loop, while the varying con-tents to be tabulated came in minimal fashion from JavaScript objects forming a catalog ormini-database.

xvii

This foreword originally appeared as the foreword to JavaScript Bible, Fourth Edition.

03_069165 fbetw.qxp 3/1/07 3:39 PM Page xvii

Page 20: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

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 compelling applications by way of script-generatedHTML and JavaScript objects. It became clear from user demonstration and feedback that web designerssought to build significant applications quickly and effectively with just a few images, HTML, andJavaScript. 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 cru-cial advantages of a scripting environment over old-school application development. Not only were theHTML and JavaScript languages comparatively easy to use, but development did not require the program-ming 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 languagefor HTML authors. By keeping the “pixel-lighting” bar low, HTML with images has made web designers outof millions of people. By keeping the event-handling bar low, JavaScript has helped many thousands ofthose designers become programmers. Perhaps the ultimate example of web development’s convergencewith application development is the Mozilla browser, wherein all of the user-interface and even some cus-tom 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). Itsinternational standard, ECMA-262 (ISO 16262), has advanced to a Third Edition. But compared to languagessuch as Perl and even Java, it is still relatively young. Work toward a Fourth Edition of the language, support-ing optional types, classes, and versioning facilities progresses within the ECMA technical committee (see theJS2 proposal to the ECMA technical committee documented 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 ofdevelopers; I owe them each a huge debt of thanks. Those developers who took up the beta releases ofNavigator 2, and disseminated vital workarounds and feature requests by e-mail and net-news, are the lan-guage’s godparents. Developer support and feedback continue to make JavaScript the eclectic, rambunctioussuccess it is.

The book in your hands compiles thousands of those developer miles with the insight of an expert guideand teacher. Danny didn’t know at the time how much inspiration I found in his HyperCard book, but itwas on my desk throughout the development of JavaScript in 1995. His energy, compassion, and clear prosehelped me keep the goal of creating “a language for all” in mind. It is enormously gratifying to write theforeword 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 espe-cially to those HTML authors who’ve so far written only a few scripts or programs—you’re in for a lifetimeof fun on the scripting road with a trusty guide at your side.

Brendan EichThe Mozilla Organization (http://www.mozilla.org)

xviii

Foreword

03_069165 fbetw.qxp 3/1/07 3:39 PM Page xviii

Page 21: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

For over 25 years, I have written the books I wished had already been written to help me learn oruse a new technology. Whenever possible, I like to get in at the very beginning of a new authoringor programming environment, feel the growing pains, and share with readers the solutions to my

struggles. This sixth edition of JavaScript Bible represents knowledge and experience accumulated overten 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 headscratching I and others have experienced through multiple generations of scriptable browsers.

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

Organization and Features of This EditionLike the previous two editions of JavaScript Bible, this sixth edition contains far more information than canbe printed and bound into a single volume. The complete contents can be found in the electronic versionof this book (in PDF form) on the CD-ROM that accompanies the book. This new edition is structured insuch a way as to supply the most commonly needed information in its entirety in the printed portion ofthe book. Content that you use to learn the fundamentals of JavaScript and reference frequently are atyour fingertips in the printed version, whereas chapters with more advanced content are in the searchableelectronic version on the CD-ROM. Here are some details about the book’s structure.

Part IPart I of the book begins with a chapter that shows how JavaScript compares with Java and discusses itsrole within the rest of the World Wide Web. The web browser and scripting world have undergone sig-nificant changes since JavaScript first arrived on the scene. That’s why Chapter 2 is devoted to address-ing challenges facing scripters who must develop applications for both single- and cross-platformbrowser audiences amid rapidly changing standards efforts. Chapter 3 provides the first foray intoJavaScript, where you get to write your first practical script.

xix

04_069165 fpref.qxp 3/1/07 3:39 PM Page xix

Page 22: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Part IIAll of Part II is handed over to a tutorial for newcomers to JavaScript. Nine lessons provide you with a grad-ual path through browser internals, basic programming skills, and genuine browser scripting with anemphasis on industry standards as supported by most of the scriptable browsers in use today. Exercises fol-low at the end of each lesson to help reinforce what you just learned and challenge you to use your newknowledge (you’ll find answers to the exercises in Appendix C). The goal of the tutorial is to equip you withsufficient experience to start scripting simple pages right away while making it easier for you to understandthe in-depth discussions and examples in the rest of the book.

Part IIIPart III, the largest section of the book, provides in-depth coverage of the document object models asimplemented in today’s browsers, including the object used for modern Ajax applications. In all referencechapters, a compatibility chart indicates the browser version that supports each object and object feature.One chapter in particular, Chapter 15, contains reference material that is shared by most of the remainingchapters of Part III. To help you refer back to Chapter 15 from other chapters, a dark tab along the outsideedge of the page shows you at a glance where the chapter is located. Additional navigation aids includeguide words near the top of most pages to indicate which object and object feature is covered on the page.

Part IVReference information for the core JavaScript language fills Part IV. As with reference chapters of Part III, theJavaScript chapters display browser compatibility charts for every JavaScript language term. Guide wordsnear the top of pages help you find a particular term quickly.

Part VSeveral appendices at the end of the book provide helpful reference information. These resources include aJavaScript and Browser Objects Quick Reference in Appendix A, a list of JavaScript reserved words inAppendix B, answers to Part II’s tutorial exercises in Appendix C, and Internet resources in Appendix D. InAppendix E, you also find information on using the CD-ROM that comes with this book, which includesnumerous bonus chapters and examples.

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

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

n Techniques for developing and debugging professional web-based applications

n Ten full-fledged JavaScript real-world applications

Another treasure trove on the CD-ROM is the Listings folder, where you’ll find over 300 ready-to-runHTML documents that serve as examples of most of the document object model and JavaScript vocabularywords in Parts III and IV. All of the bonus chapter example listings are also included. You can run theseexamples with your JavaScript-enabled browser, but be sure to use the index.html page in the Listingsfolder as a gateway to running the listings. I could have provided you with humorous little sample codefragments out of context, but I think that seeing full-fledged HTML documents (simple though they maybe) for employing these concepts is important. I intentionally omitted the script listings from the tutorial

xx

Preface

04_069165 fpref.qxp 3/1/07 3:39 PM Page xx

Page 23: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

part (Part II) of this book to encourage you to type the scripts. I believe you learn a lot, even by aping list-ings from the book, as you get used to the rhythms of typing scripts in documents.

Be sure to check out the Chapter 13 listing file called evaluator.html. Many segments of Parts III andIV 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 featureworks.

The Quick Reference from Appendix A is in PDF format on the CD-ROM for you to print out and assembleas a handy reference, if desired. Adobe Reader is also included on the CD-ROM, in case you don’t alreadyhave it, so that you can read both of these PDF files.

Prerequisites to Learning JavaScriptAlthough this book doesn’t demand that you have a great deal of programming experience behind you, themore Web pages you’ve created with HTML, the easier you will find it to understand how JavaScript inter-acts with the familiar elements you normally place in your pages. Occasionally, you will need to modifyHTML tags to take advantage of scripting. If you are familiar with those tags already, the JavaScript enhance-ments will be simple to digest.

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. You shouldalso be familiar with some of the latest document markup standards, such as XHTML and Cascading StyleSheets (CSS). You don’t need to be an expert, by any means. Web searches for these terms will uncovernumerous tutorials on the subjects.

If you’ve never programmed beforeDon’t be put off by the size of this book. 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. Unlikedeveloping a full-fledged monolithic application (such as the productivity programs you buy in the stores),JavaScript enables you to 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 thecomputer to follow. We humans follow instructions all the time, even if we don’t realize it. Traveling to afriend’s house is a sequence of small instructions: Go three blocks that way; turn left here; turn right there.Amid these instructions are some decisions that we have to make: If the stoplight is red, then stop; if thelight is green, then go; if the light is yellow, then floor it. Occasionally, we must repeat some operations sev-eral times (kind of like having to go around the block until a parking space opens up). A computer programnot only contains the main sequence of steps, but it also anticipates what decisions or repetitions may beneeded to accomplish the program’s goal (such as how to handle the various states of a stoplight or what todo 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 languagewants its words and numbers organized in these instructions. Such rules are called syntax, the same as in aliving language. Because computers generally are dumb electronic hulks, they aren’t very forgiving if you

xxi

Preface

04_069165 fpref.qxp 3/1/07 3:39 PM Page xxi

Page 24: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

don’t communicate with them in the specific language they understand. When speaking to another human,you can flub a sentence’s syntax and still have a good chance of the other person’s understanding you fully.Not so with computer programming languages. If the syntax isn’t perfect (or at least within the language’srange of knowledge that it can correct), the computer has the brazenness to tell you that you have made asyntax error.

The best thing you can do is to just chalk up the syntax errors you receive as learning experiences. Evenexperienced programmers make them. Every syntax error you get—and every resolution of that error madeby rewriting the wayward statement—adds to your knowledge of the language.

If you’ve done a little programming beforeProgramming experience in a procedural language, such as BASIC, may almost be a hindrance rather than ahelp to learning JavaScript. Although you may have an appreciation for precision in syntax, the overall con-cept of how a program fits into the world is probably radically different from JavaScript. Part of this has todo with the typical tasks a script performs (carrying out a very specific task in response to user actionwithin 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 screenand everything that happens under the hood. When the program first runs, a great deal of code is dedicatedto setting up the visual environment. Perhaps the screen contains several text entry fields or clickable but-tons. To determine which button a user clicks, the program examines the coordinates of the click and com-pares those coordinates against a list of all button coordinates on the screen. Program execution thenbranches out to perform the instructions reserved for clicking in that space.

Object-oriented programming is almost the inverse of that process. A button is considered an object—something tangible. An object has properties, such as its label, size, alignment, and so on. An object mayalso contain a script. At the same time, the system software and browser, working together, can send a mes-sage to an object—depending on what the user does—to trigger the script. For example, if a user clicks in atext entry field, the system/browser tells the field that somebody has clicked there (that is, has set the focusto that field), giving the field the task of deciding what to do about it. That’s where the script comes in. Thescript is connected to the field, and it contains the instructions that the field carries out after the user acti-vates it. Another set of instructions may control what happens when the user types an entry and tabs orclicks 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 ofinstructions that are carried out in order. But when dealing with data from form elements, these instructionswork with the object-based nature of JavaScript. The form is an object; each radio button or text box is anobject as well. The script then acts on the properties of those objects to get some work done.

Making the transition from procedural to object-oriented programming may be the most difficult challengefor you. When I was first introduced to object-oriented programming a number of years ago, I didn’t get itat first. But when the concept clicked—a long, pensive walk helped—so many light bulbs went on insidemy head that I thought I might glow in the dark. From then on, object orientation seemed to be the onlysensible way to program.

If you’ve programmed in C beforeBy borrowing syntax from Java (which, in turn, is derived from C and C++), JavaScript shares many syntacti-cal characteristics with C. Programmers familiar with C will feel right at home. Operator symbols, conditionalstructures, and repeat loops follow very much in the C tradition. You will be less concerned about data typesin JavaScript than you are in C. In JavaScript, a variable is not restricted to any particular data type.

xxii

Preface

04_069165 fpref.qxp 3/1/07 3:39 PM Page xxii

Page 25: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

With so much of the JavaScript syntax familiar to you, you will be able to concentrate on document objectmodel concepts, which may be entirely new to you. You will still need a good grounding in HTML to putyour expertise to work in JavaScript.

If you’ve programmed in Java beforeDespite the similarity in their names, the two languages share only surface aspects: loop and conditionalconstructions, C-like dot object references, curly braces for grouping statements, several keywords, and afew other attributes. Variable declarations, however, are quite different, because JavaScript is a loosely typedlanguage. A variable can contain an integer value in one statement and a string in the next (although I’m notsaying that this is good style). What Java refers to as methods, JavaScript calls methods (when associatedwith a predefined object) or functions (for scripter-defined actions). JavaScript methods and functions mayreturn 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-orientednotions of classes, inheritance, instantiation, and message passing. These aspects are simply non-issueswhen scripting. At the same time, however, the designers of JavaScript knew that you’d have some hard-to-break habits. For example, although JavaScript does not require a semicolon at the end of each statementline, if you type one in your JavaScript source code, the JavaScript interpreter won’t balk.

If you’ve written scripts (or macros) beforeExperience with writing scripts in other authoring tools or macros in productivity programs is helpful forgrasping a number of JavaScript concepts. Perhaps the most important concept is the idea of combining ahandful of statements to perform a specific task on some data. For example, you can write a macro inMicrosoft Excel that performs a data transformation on daily figures that come in from a corporate financialreport on another computer. The macro is built into the Macro menu, and you run it by choosing thatmenu item whenever a new set of figures arrives.

Some modern programming environments, such as Visual Basic, resemble scripting environments in someways. They present the programmer with an interface builder, which does most of the work of displayingscreen objects with which the user will interact. A big part of the programmer’s job is to write little bits ofcode that are executed when a user interacts with those objects. A great deal of the scripting you will dowith JavaScript matches that pattern exactly. In fact, those environments resemble the scriptable browserenvironment in another way: They provide a finite set of predefined objects that have fixed sets of proper-ties and behaviors. This predictability makes learning the entire environment and planning an applicationeasier to accomplish.

Formatting and Naming ConventionsThe script listings and words in this book are presented in a monospaced font to set them apart from therest of the text. Because of restrictions in page width, lines of script listings may, from time to time, breakunnaturally. In such cases, the remainder of the script appears in the following line, flush with the left mar-gin of the listing, just as they would appear in a text editor with word wrapping turned on. If these linebreaks cause you problems when you type a script listing into a document yourself, I encourage you toaccess 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 anobject model or language feature that requires a specific minimum version of one browser or another. To

xxiii

Preface

04_069165 fpref.qxp 3/1/07 3:39 PM Page xxiii

Page 26: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

make it easier to spot in the text when a particular browser and browser version is required, most browserreferences consist of an abbreviation and a version number. For example, WinIE5 means Internet Explorer 5for Windows; NN4 means Netscape Navigator 4 for any operating system; Moz stands for the modernMozilla browser (from which Firefox, Netscape 6 or later, and Camino are derived); and Safari is Apple’sown browser for Mac OS X. If a feature is introduced with a particular version of browser and is supportedin subsequent versions, a plus symbol (+) follows the number. For example, a feature marked WinIE5.5+indicates that Internet Explorer 5.5 for Windows is required at a minimum, but the feature is also availablein WinIE7 and probably future WinIE versions. If a feature was implemented in the first release of a modernbrowser, a plus symbol immediately follows the browser family name, such as Moz+ for all Mozilla-basedbrowsers. Occasionally, a feature or some highlighted behavior applies to only one browser. For example, afeature marked NN4 means that it works only in Netscape Navigator 4.x. A minus sign (for example,WinIE-) means that the browser does not support the item being discussed.

The format of HTML and code listings in this edition follow XHTML coding conventions, which dictate all-lowercase tag and attribute names, as well as self-closing tags that do not act as containers (such as theXHTML <br /> tag in place of the HTML <br> tag).

CROSS-REFCROSS-REFCAUTION CAUTIONTIPTIPNOTENOTE

xxiv

Preface

Note, Tip, Caution, and Cross-Reference icons occasionally appearin the book to flag important points or suggest where to find moreinformation.

04_069165 fpref.qxp 3/1/07 3:39 PM Page xxiv

Page 27: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Getting Started with JavaScript

IN THIS PARTChapter 1JavaScript’s Role in the WorldWide Web and Beyond

Chapter 2Authoring Challenges Amid the Browser Wars

Chapter 3Your First JavaScript Script

05_069165 pt01.qxp 3/1/07 3:39 PM Page 1

Page 28: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

05_069165 pt01.qxp 3/1/07 3:39 PM Page 2

Page 29: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Many of the technologies that make the World Wide Web possible havefar exceeded their original goals. Envisioned at the outset as a mediumfor publishing static text and image content across a network, the Web

is forever being probed, pushed, and pulled by content authors. By taking forgranted so much of the “dirty work” of conveying the bits between server andclient computers, content developers and programmers dream of exploiting thatconnection to generate new user experiences and practical applications. It’s notuncommon for a developer community to take ownership of a technology andmold it to do new and exciting things. But with so many Web technologies —especially browser programming with JavaScript — being within reach of every-day folks, we have witnessed an unprecedented explosion in turning the WorldWide Web from a bland publishing medium into a highly interactive, operatingsystem–agnostic authoring platform.

The JavaScript language, working in tandem with related browser features, is aWeb-enhancing technology. When employed on the client computer, the lan-guage can help turn a static page of content into an engaging, interactive, andintelligent experience. Applications can be as subtle as welcoming a site’s visitorwith the greeting “Good morning!” when it is morning in the client computer’stime zone — even though it is dinnertime where the server is located. Or applica-tions can be much more obvious, such as delivering the content of a slide showin a one-page download while JavaScript controls the sequence of hiding, show-ing, and “flying slide” transitions while navigating through the presentation.

Of course, JavaScript is not the only technology that can give life to drab Webcontent. Therefore, it is important to understand where JavaScript fits within thearray of standards, tools, and other technologies at your disposal. The alternativetechnologies described in this chapter are HTML, Cascading Style Sheets (CSS),server programs, and plug-ins. In most cases, JavaScript can work side by sidewith these other technologies, even though the hype around some make themsound like one-stop shopping places for all your interactive needs. That’s rarelythe case. Finally, you learn about the origins of JavaScript and what role it playsin today’s advanced Web browsers.

3

IN THIS CHAPTERHow JavaScript blends withother Web-authoringtechnologies

The history of JavaScript

What kinds of jobs you shouldand should not entrust toJavaScript

JavaScript’s Role in the World Wide Web and Beyond

06_069165 ch01.qxp 3/1/07 3:40 PM Page 3

Page 30: JavaScript Bible · 2013. 7. 23. · Praise for Danny Goodman’s JavaScript®Bible “JavaScript® Bible is the definitive resource in JavaScript programming. I am never more than

Competing for Web TrafficWeb-page publishers revel in logging as many visits to their sites as possible. Regardless of the questionableaccuracy of Web page hit counts, a site consistently logging 10,000 dubious hits per week is clearly far morepopular than one with 1,000 dubious hits per week. Even if the precise number is unknown, relative popu-larity is a valuable measure. Another useful number is how many links from outside pages lead to a site. Apopular site will have many other sites pointing to it — a key to earning high visibility in Web searches.

Encouraging people to visit a site frequently is the Holy Grail of Web publishing. Competition for viewers isenormous. Not only is the Web like a 50 million–channel television, but also, the Web competes for view-ers’ attention with all kinds of computer-generated information. That includes anything that appearsonscreen as interactive multimedia.

Users of entertainment programs; multimedia encyclopedias; and other colorful, engaging, and mouse-finger-numbing actions are accustomed to high-quality presentations. Frequently, these programs sport first-rategraphics, animation, live-action video, and synchronized sound. By contrast, the lowest-common-denominatorWeb page has little in the way of razzle-dazzle. Even with the help of Dynamic HTML and stylesheets, the lay-out of pictures and text is highly constrained compared with the kinds of desktop publishing documents yousee all the time. Regardless of the quality of its content, an unscripted, vanilla HTML document is flat. At best,interaction is limited to whatever navigation the author offers in the way of hypertext links or forms whosefilled-in content magically disappears into the Web site’s server.

Other Web TechnologiesWith so many ways to spice up Web sites and pages, you can count on competitors for your site’s visitors todo their darnedest to make their sites more engaging than yours. Unless you are the sole purveyor of infor-mation that is in high demand, you continually must devise ways to keep your visitors coming back andentice new ones. If you design for an intranet, your competition is the drive for improved productivity bycolleagues who use the internal Web sites for getting their jobs done.

These are all excellent reasons why you should care about using one or more Web technologies to raise yourpages above the noise. Let’s look at the major technologies you should know about.

Hypertext Markup Language (HTML and XHTML)As an outgrowth of SGML (Standard Generalized Markup Language), HTML is generally viewed as nothingmore than a document formatting, or tagging, language. The tags (inside <> delimiter characters) instruct aviewer program (the browser or, more generically, the client) how to display chunks of text or images.

Relegating HTML to the category of a tagging language does disservice not only to the effort that goes intofashioning a first-rate Web page, but also to the way users interact with the pages. To my way of thinking,any collection of commands and other syntax that directs the way users interact with digital information isprogramming. With HTML, a Web-page author controls the user experience with the content just as theengineers who program Microsoft Excel craft the way users interact with spreadsheet content and functions.

Version 4.0 and later of the published HTML standards endeavor to define the purpose of HTML as assign-ing context to content, leaving the appearance to a separate standard for stylesheets. In other words, it’s notHTML’s role to signify that some text is italic but, rather, to signify why it is italic. For example, you wouldtag a chunk of text that conveys emphasis (via the <em> tag) regardless of how the stylesheet or browser setsthe appearance of that emphasized text.

4

Getting Started with JavaScriptPart I

06_069165 ch01.qxp 3/1/07 3:40 PM Page 4