Tải bản đầy đủ (.pdf) (1,200 trang)

JavaScript Bible®Sixth EditionDanny Goodman with Michael MorrisonWith a foreword by Brendan pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (13.12 MB, 1,200 trang )

JavaScript
®
Bible
Sixth 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
more free ebooks download links:

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™
more free ebooks download links:

Praise for Danny Goodman’s
JavaScript
®
Bible
“JavaScript
®
Bible is the definitive resource in JavaScript programming. I am never more than three feet
from my copy.”
—Steve Reich, CEO, PageCoders
“This book is a must-have for any web developer or programmer.”
—Thoma Lile, President, Kanis Technologies, Inc.
“Outstanding book. I would recommend this book to anyone interested in learning to develop advanced
Web sites. Mr. Goodman did an excellent job of organizing this book and writing it so that even a 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 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
“Danny Goodman is very good at leading the reader into the subject. JavaScript
®
Bible has everything we
could possibly need.”
—Philip Gurdon
“An excellent book that builds solidly from whatever level the reader is at. A book that is both witty and
educational.”
—Dave Vane
“I continue to use the book on a daily basis and would be lost without it.”
—Mike Warner, Founder, Oak Place Productions


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
more free ebooks download links:

01_069165 ffirs.qxp 3/1/07 3:38 PM Page ii
more free ebooks download links:

JavaScript
®
Bible
Sixth 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
more free ebooks download links:

JavaScript
®
Bible, Sixth Edition
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.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 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA
01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal
Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)
572-4355, or online at
/>LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO
REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE
CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR
EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN
MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT
THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL
SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL
PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR
DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS
WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT
THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY
PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET
WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK
WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services or to obtain technical support, please contact our Customer
Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.
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 2007
005.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 a
registered trademark of Sun Microsystems Inc. in the United States and other countries. All other trademarks are the property of
their 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 in
electronic books.
01_069165 ffirs.qxp 3/1/07 3:38 PM Page iv
more free ebooks download links:

About the Authors
Danny Goodman is the author of numerous critically acclaimed and best-selling books, including The
Complete HyperCard Handbook
, Danny Goodman’s AppleScript Handbook, Dynamic HTML: The Definitive
Reference
, and JavaScript & DHTML Cookbook. He is a renowned authority and expert teacher of computer
scripting languages. 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.
Michael Morrison is a writer, developer, toy inventor, and author of a variety of books covering topics such
as 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 Beginning
Game 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
more free ebooks download links:

Credits
Acquisitions Editor
Kit Kemper
Senior Development Editor
Kevin Kent
Copy Editor
Travis Henderson
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group
Publisher
Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Project Coordinator
Lynsey Osborn
Graphics and Production Specialists
Brooke Graczyk
Joyce Haughey
Jennifer Mayberry
Alicia B. South

Quality Control Technicians
David Faust
John Greenough
Media Development Project Supervisor
Laura Atkinson
Media Development Specialist
Kate Jenkins
Proofreading
David Faust
Kathy Simpson
Sossity Smith
Indexing
Valerie Haynes Perry
Anniversary Logo Design
Richard Pacifico
01_069165 ffirs.qxp 3/1/07 3:38 PM Page vi
more free ebooks download links:

T
his 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. When
you 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 Michael
made 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 many
readers of the earlier editions of this book for investing in this ongoing effort. I wish I had the space here
to acknowledge by name so many who have sent e-mail notes and suggestions: Your input has been
most welcome and greatly appreciated.
vii

01_069165 ffirs.qxp 3/1/07 3:38 PM Page vii
more free ebooks download links:

01_069165 ffirs.qxp 3/1/07 3:38 PM Page viii
more free ebooks download links:

About the Authors v
Acknowledgments vii
Foreword xvii
Preface xix
Part I: Getting Started with JavaScript 1
Chapter 1: JavaScript’s Role in the World Wide Web and Beyond . . . . . . . 3
Competing for Web Traffic 4
Other Web Technologies 4
JavaScript: A Language for All 6
JavaScript: The Right Tool for the Right Job 8
Chapter 2: Authoring Challenges Amid the Browser Wars . . . . . . . . . . . 9
Leapfrog 9
Duck and Cover 10
Compatibility Issues Today 11
Developing a Scripting Strategy 14
Chapter 3: Your First JavaScript Script . . . . . . . . . . . . . . . . . . . . . 17
The Software Tools 17
Setting Up Your Authoring Environment 18
What Your First Script Will Do 21
Entering Your First Script 21
Examining the Script 23
Have Some Fun 25
Part II: JavaScript Tutorial 27
Chapter 4: Browser and Document Objects . . . . . . . . . . . . . . . . . . 29

Scripts Run the Show 29
When to Use JavaScript 30
The Document Object Model 31
When a Document Loads 33
Object References 36
Node Terminology 38
What Defines an Object? 39
Exercises 43
ix
02_069165 ftoc.qxp 3/1/07 4:02 PM Page ix
more free ebooks download links:

Chapter 5: Scripts and HTML Documents . . . . . . . . . . . . . . . . . . . 45
Where Scripts Go in Documents 45
JavaScript Statements 49
When Script Statements Execute 49
Viewing Script Errors 52
Scripting versus Programming 54
Exercises 55
Chapter 6: Programming Fundamentals, Part I. . . . . . . . . . . . . . . . . 57
What Language Is This? 57
Working with Information 57
Variables 58
Expressions and Evaluation 60
Data Type Conversions 62
Operators 64
Exercises 65
Chapter 7: Programming Fundamentals, Part II . . . . . . . . . . . . . . . . 67
Decisions and Loops 67
Control Structures 68

About Repeat Loops 69
Functions 70
About Curly Braces 74
Arrays 74
Exercises 78
Chapter 8: Window and Document Objects . . . . . . . . . . . . . . . . . . 81
Top-Level Objects 81
The window Object 82
Window Properties and Methods 85
The location Object 87
The navigator Object 88
The document Object 88
Exercises 93
Chapter 9: Forms and Form Elements. . . . . . . . . . . . . . . . . . . . . . 95
The form Object 95
Form Controls as Objects 97
Passing Form Data and Elements to Functions 104
Submitting and Prevalidating Forms 106
Exercises 108
Chapter 10: Strings, Math, and Dates . . . . . . . . . . . . . . . . . . . . . 109
Core Language Objects 109
String Objects 110
The Math Object 113
The Date Object 114
Date Calculations 115
Exercises 117
x
Contents
02_069165 ftoc.qxp 3/1/07 4:02 PM Page x
more free ebooks download links:


Chapter 11: Scripting Frames and Multiple Windows . . . . . . . . . . . . 119
Frames: Parents and Children 119
References Among Family Members 121
Frame-Scripting Tips 123
About iframe Elements 124
Controlling Multiple Frames: Navigation Bars 124
References for Multiple Windows 126
Exercises 128
Chapter 12: Images and Dynamic HTML . . . . . . . . . . . . . . . . . . . 129
The Image Object 129
Rollovers Without Scripts 135
The javascript: Pseudo-URL 137
Popular Dynamic HTML Techniques 138
Exercises 140
Part III: Document Objects Reference 141
Chapter 13: JavaScript Essentials . . . . . . . . . . . . . . . . . . . . . . . 143
JavaScript Versions 143
Core Language Standard: ECMAScript 144
Embedding Scripts in HTML Documents 145
Browser Version Detection 149
Designing for Compatibility 154
Language Essentials for Experienced Programmers 158
Onward to Object Models 161
Chapter 14: Document Object Model Essentials . . . . . . . . . . . . . . . 163
The Object Model Hierarchy 163
How Document Objects Are Born 166
Object Properties 166
Object Methods 167
Object Event Handlers 168

Object Model Smorgasbord 169
Basic Object Model 169
Basic Object Model Plus Images 170
Navigator 4–Only Extensions 170
Internet Explorer 4+ Extensions 171
Internet Explorer 5+ Extensions 174
The W3C DOM 175
Scripting Trends 190
Standards Compatibility Modes (DOCTYPE Switching) 191
Where to Go from Here 192
Chapter 15: Generic HTML Element Objects. . . . . . . . . . . . . . . . . 195
Generic Objects 196
xi
Contents
02_069165 ftoc.qxp 3/1/07 4:02 PM Page xi
more free ebooks download links:

Chapter 16: Window and Frame Objects . . . . . . . . . . . . . . . . . . . 369
Window Terminology 369
Frames 370
window Object 376
frame Element Object 471
frameset Element Object 478
iframe Element Object 484
popup Object 490
Chapter 17: Location and History Objects . . . . . . . . . . . . . . . . . . 495
location Object 496
history Object 513
Chapter 18: The Document and Body Objects . . . . . . . . . . . . . . . . 519
document Object 520

body Element Object 587
TreeWalker Object 595
Chapter 19: Link and Anchor Objects. . . . . . . . . . . . . . . . . . . . . 599
Anchor, Link, and a Element Objects 600
Chapter 20: Image, Area, Map, and Canvas Objects . . . . . . . . . . . . . 607
Image and img Element Objects 607
area Element Object 626
map Element Object 630
canvas Element Object 634
Chapter 21: The Form and Related Objects. . . . . . . . . . . . . . . . . . 645
The Form in the Object Hierarchy 645
form Object 646
fieldset and legend Element Objects 663
label Element Object 665
Scripting and Web Forms 2.0 666
Chapter 21: Button Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 669
The button Element Object, and the Button, Submit, and Reset Input Objects 669
checkbox Input Object 675
radio Input Object 682
image Input Object 688
Chapter 23: Text-Related Form Objects. . . . . . . . . . . . . . . . . . . . 691
Text Input Object 691
password Input Object 706
hidden Input Object 707
textarea Element Object 708
Chapter 24: Select, Option, and FileUpload Objects . . . . . . . . . . . . 713
select Element Object 713
option Element Object 732
optgroup Element Object 734
file Input Element Object 736

xii
Contents
02_069165 ftoc.qxp 3/1/07 4:02 PM Page xii
more free ebooks download links:

Chapter 25: Event Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
Why “Events”? 740
Event Propagation 741
Referencing the event object 753
Binding Events 754
event Object Compatibility 758
Dueling Event Models 760
Event Types 763
IE4+ event Object 766
NN6+/Moz/Safari event Object 787
Chapter 26: Style Sheet and Style Objects . . . . . . . . . . . . . . . . . . 811
Making Sense of the Object Names 812
Imported Stylesheets 813
Reading Style Properties 813
style Element Object 814
styleSheet Object 816
cssRule and rule Objects 825
currentStyle, runtimeStyle, and style Objects 828
filter Object 854
Chapter 27: Ajax and XML. . . . . . . . . . . . . . . . . . . . . . . . . . . 867
Elements and Nodes 868
xml Element Object 869
XMLHttpRequest Object 871
Part IV: JavaScript Core Language Reference 881
Chapter 28: The String Object. . . . . . . . . . . . . . . . . . . . . . . . . 883

String and Number Data Types 883
String Object 886
String Utility Functions 908
URL String Encoding and Decoding 912
Chapter 29: The Math, Number, and Boolean Objects. . . . . . . . . . . . 913
Numbers in JavaScript 913
Math Object 919
Number Object 922
Boolean Object 926
Chapter 30: The Date Object . . . . . . . . . . . . . . . . . . . . . . . . . 927
Time Zones and GMT 927
The Date Object 929
Validating Date Entries in Forms 941
xiii
Contents
02_069165 ftoc.qxp 3/1/07 4:02 PM Page xiii
more free ebooks download links:

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

If and If. . .Else Decisions 969
Conditional Expressions 974
Repeat (for) Loops 975
The while Loop 979
The do-while Loop 980
Looping through Properties (for-in) 981
The with Statement 982
Labeled Statements 983
The switch Statement 985
Exception Handling 988
Using try-catch-finally Constructions 990
Throwing Exceptions 993
Error Object 997
Chapter 33: JavaScript Operators . . . . . . . . . . . . . . . . . . . . . . 1001
Operator Categories 1001
Comparison Operators 1002
Equality of Disparate Data Types 1003
Connubial Operators 1005
Assignment Operators 1008
Boolean Operators 1009
Bitwise Operators 1013
Object Operators 1014
Miscellaneous Operators 1018
Operator Precedence 1020
Chapter 34: Functions and Custom Objects. . . . . . . . . . . . . . . . . 1023
Function Object 1023
Function Application Notes 1032
Creating Your Own Objects with Object-Oriented JavaScript 1039
Object-Oriented Concepts 1052
Object Object 1055

Chapter 35: Global Functions and Statements . . . . . . . . . . . . . . . 1061
Functions 1062
Statements 1070
xiv
Contents
02_069165 ftoc.qxp 3/1/07 4:02 PM Page xiv
more free ebooks download links:

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 . . . . . . . . . . . . . . . . . 1089
Chapter 4 Answers 1089
Chapter 5 Answers 1090
Chapter 6 Answers 1092
Chapter 7 Answers 1092
Chapter 8 Answers 1097
Chapter 9 Answers 1098
Chapter 10 Answers 1101
Chapter 11 Answers 1103
Chapter 12 Answers 1103
Appendix D: JavaScript and DOM Internet Resources . . . . . . . . . . . 1105
Support and Updates for This Book 1105
Newsgroups 1106
FAQs 1106
Online Documentation 1107
World Wide Web 1107
Appendix E: What’s on the CD-ROM . . . . . . . . . . . . . . . . . . . . 1109
System Requirements 1109
Disc Contents 1110

Troubleshooting 1111
Customer 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
more free ebooks download links:

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
more free ebooks download links:

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 documents. 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 document 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:
n
“Java-lite” syntax. Although the “natural language” syntax of HyperTalk was fresh in my
mind after a friend lent me
The Complete HyperCard Handbook by some fellow named
Goodman, the Next Big Thing weighed heavier, especially in light of another goal: scripting
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 insisting 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 writing short snippets of code,
quickly and without fuss.
n
Events for HTML elements. Buttons should have onClick event handlers. Documents load
and unload from windows, so windows should have
onLoad and onUnload handlers. Users
and scripts submit forms: thus the

onSubmit handler. Although not initially as flexible as
HyperCard’s messages (whose handlers inspired the onEvent naming convention), 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 modern browsers has fully flexible control
over 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 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 parameter. Although
prototypes didn’t appear until Navigator 3, they were prefigured in Version 2 by quoted text
being 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 speak
HTML, 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 of
tables 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 or
mini-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
more free ebooks download links:

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-generated
HTML and JavaScript objects. It became clear from user demonstration and feedback that web designers
sought to build significant 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: />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 the
HTML 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 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 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). 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, support-
ing optional types, classes, and versioning facilities progresses within the ECMA technical committee (see the
JS2 proposal to the ECMA technical committee documented at
/>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 developers who took up the beta releases of
Navigator 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, rambunctious
success it is.
The book in your hands compiles thousands of those developer miles with the insight of an expert guide
and teacher. Danny didn’t know at the time how much inspiration I found in his HyperCard book, but it
was on my desk throughout the development of JavaScript in 1995. His energy, compassion, and clear prose
helped me keep the goal of creating “a language for all” in mind. It is enormously gratifying to write the

foreword 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 lifetime
of fun on the scripting road with a trusty guide at your side.
Brendan Eich
The Mozilla Organization (
)
xviii
Foreword
03_069165 fbetw.qxp 3/1/07 3:39 PM Page xviii
more free ebooks download links:

F
or over 25 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 growing pains, and share with readers the solutions to my
struggles. This sixth edition of
JavaScript Bible represents knowledge and experience accumulated over
ten 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.
Although the earliest editions of this book focused on the then predominant Netscape Navigator
browser, the browser market share landscape has changed through the years. For many years, Microsoft
took a strong lead with its Internet Explorer, but more recently, other browsers that support industry
standards are finding homes on users’ computers. The situation still leaves an age-old dilemma for con-
tent developers: designing scripted content that functions equally well in both standards-compliant and
proprietary 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 the
two so that they work on the wide array of browsers visiting your sites or web applications. Empowering

you to design and write good scripts is my passion, regardless of browser. It’s true that my bias is toward
industry standards, but not to the exclusion of proprietary features that may be necessary to get your
content and scripting ideas flowing equally well on today’s and tomorrow’s browsers.
Organization and Features of This Edition
Like the previous two editions of JavaScript Bible, this sixth edition contains far more information than can
be printed and bound into a single volume. The complete contents can be found in the electronic version
of this book (in PDF form) on the CD-ROM that accompanies the book. This new edition is structured in
such a way as to supply the most commonly needed information in its entirety in the printed portion of
the book. Content that you use to learn the fundamentals of JavaScript and reference frequently are at
your fingertips in the printed version, whereas chapters with more advanced content are in the searchable
electronic version on the CD-ROM. Here are some details about the book’s structure.
Part I
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 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-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.
xix
04_069165 fpref.qxp 3/1/07 3:39 PM Page xix
more free ebooks download links:

Part II
All 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 an
emphasis 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 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.

Part III
Part III, the largest section of the book, provides in-depth coverage of the document object models as
implemented in today’s browsers, including the object used for modern Ajax applications. In all reference
chapters, 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 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 navigation aids include
guide words near the top 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 reference chapters of Part III, the
JavaScript chapters display browser compatibility charts for every JavaScript language term. Guide words
near the top of pages help you find a particular term quickly.
Part V
Several appendices at the end of the book provide helpful reference information. These resources include a
JavaScript and Browser Objects Quick Reference in Appendix A, a list of JavaScript reserved words in
Appendix B, answers to Part II’s tutorial exercises in Appendix C, and Internet resources in Appendix D. In
Appendix E, you also find information on using the CD-ROM that comes with this book, which includes
numerous bonus chapters and examples.
CD-ROM
The CD-ROM is a gold mine of information. It begins with a PDF version of the entire contents of this sixth
edition 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-run
HTML documents that serve as examples of most of the document object model and JavaScript vocabulary

words in Parts III and IV. All of the bonus chapter example listings are also included. You can run these
examples with your JavaScript-enabled browser, but be sure to use the
index.html page in the Listings
folder as a gateway to running the listings. I could have provided you with humorous little sample code
fragments out of context, but I think that seeing full-fledged HTML documents (simple though they may
be) 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
more free ebooks download links:

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 and
IV invite you to try out an object model or language feature with the help of an interactive workbench,
called The Evaluator—a
JavaScript Bible exclusive! You see instant results and quickly learn how the feature
works.
The Quick Reference from Appendix A is in PDF format on the CD-ROM for you to print out and assemble
as a handy reference, if desired. Adobe Reader is also included on the CD-ROM, in case you don’t already
have it, so that you can read both of these PDF files.
Prerequisites to Learning JavaScript
Although this book doesn’t demand that you have a great deal of programming experience behind you, the
more Web pages you’ve created with HTML, the easier you will find it to understand how JavaScript inter-
acts with the familiar elements you normally place in your pages. Occasionally, you will need to modify
HTML tags to take advantage of scripting. If you are familiar with those tags already, the JavaScript 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 should
also be familiar with some of the latest document markup standards, such as XHTML and Cascading Style
Sheets (CSS). You don’t need to be an expert, by any means. Web searches for these terms will uncover
numerous tutorials on the subjects.
If you’ve never programmed before
Don’t be put off by the size of this book. JavaScript may not be the easiest language in the world to learn,
but believe me, it’s a far cry from having to learn a full programming language, such as Java or C. Unlike
developing a full-fledged monolithic application (such as the productivity programs you buy in the stores),
JavaScript 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 the
computer to follow. We humans follow instructions all the time, even if we don’t realize it. Traveling to a
friend’s house is a sequence of small instructions: Go three blocks that way; turn left here; turn right there.
Amid these instructions are some decisions that we have to make: If the stoplight is red, then stop; if the
light is green, then go; if the light is yellow, then floor it. 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 program
not only contains the main sequence of steps, but it also anticipates what decisions or repetitions may be
needed to accomplish the program’s goal (such as how to handle the various states of a stoplight or what to
do if someone just stole the parking spot you were aiming for).
The initial hurdle of learning to program is becoming comfortable with the way a programming language
wants its words and numbers organized in these instructions. Such rules are called syntax, the same as in a
living language. 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
more free ebooks download links:

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’s

range of knowledge that it can correct), the computer has the brazenness to tell you that you have made a
syntax error.
The best thing you can do is to just chalk up the syntax errors you receive as learning experiences. Even
experienced programmers make them. Every syntax error you get—and every resolution of that error made
by rewriting the wayward statement—adds to your knowledge of the language.
If you’ve done a little programming before
Programming experience in a procedural language, such as BASIC, may almost be a hindrance rather than a
help 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 to
do with the typical tasks a script performs (carrying out a very specific task in response to user action
within a web page), but a large part also has to do with the nature of object-oriented programming.
In a typical procedural program, the programmer is responsible for everything that appears on the screen
and everything that happens under the hood. When the program first runs, a great deal of code is dedicated
to setting up the visual environment. Perhaps the screen contains several text entry fields or clickable 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 then
branches out to perform the instructions reserved for clicking in that space.
Object-oriented programming is almost the inverse of that process. A button is considered an object—
something tangible. An object has properties, such as its label, size, alignment, and so on. An object may
also contain a script. At the same time, the system software and browser, working together, can send a mes-
sage to an object—depending on what the user does—to trigger the script. For example, if a user clicks in a
text entry field, the system/browser tells the field that somebody has clicked there (that is, has set the focus
to that field), giving the field the task of deciding what to do about it. That’s where the script comes in. The
script is connected to the field, and it contains the instructions that the field carries out after the user acti-
vates it. Another set of instructions may control what happens when the user types an entry and tabs or
clicks out of the field, thereby changing the content of the field.
Some of the scripts you write may seem to be procedural in construction: They contain a simple list of
instructions that are carried out in order. But when dealing with data from form elements, these instructions
work with the object-based nature of JavaScript. The form is an object; each radio button or text box is an
object as well. The script then acts on the properties of those objects to get some work done.

Making the transition from procedural to object-oriented programming may be the most difficult challenge
for you. When I was first introduced to object-oriented programming a number of years ago, I didn’t get it
at first. But when the concept clicked—a long, pensive walk helped—so many light bulbs went on inside
my head that I thought I might glow in the dark. From then on, object orientation seemed to be the only
sensible way to program.
If you’ve programmed in C before
By borrowing syntax from Java (which, in turn, is derived from C and C++), JavaScript shares many syntacti-
cal characteristics with C. Programmers familiar with C will feel right at home. Operator symbols, conditional
structures, and repeat loops follow very much in the C tradition. You will be less concerned about data types
in JavaScript than you are in C. In JavaScript, a variable is not restricted to any particular data type.
xxii
Preface
04_069165 fpref.qxp 3/1/07 3:39 PM Page xxii
more free ebooks download links:

×