
Table of Contents
Praise for Javascript® Bible
Title Page
Copyright
Dedication
About the Authors
Credits
Acknowledgments
Introduction
Organization and Features of This Edition
Prerequisites to Learning JavaScript
Formatting and Naming Conventions
Part I: Getting Started with JavaScript
Chapter 1: JavaScript's Role in the World Wide Web and Beyond
Competing for Web Traffic
Other Web Technologies
JavaScript: A Language for All
JavaScript: The Right Tool for the Right Job
Chapter 2: Developing a Scripting Strategy
Browser Leapfrog
Duck and Cover
Compatibility Issues Today
Developing a Scripting Strategy
Chapter 3: Selecting and Using Your Tools
The Software Tools
Setting Up Your Authoring Environment
Validate, Validate, Validate
Creating Your First Script
Chapter 4: JavaScript Essentials
Combining JavaScript with HTML
Designing for Compatibility
Language Essentials for Experienced Programmers
Part II: JavaScript Tutorial
Chapter 5: Your First JavaScript Script
What Your First Script Will Do
Entering Your First Script
Have Some Fun
Exercises
Chapter 6: Browser and Document Objects
Scripts Run the Show
When to Use JavaScript
The Document Object Model
When a Document Loads
Object References
Node Terminology
What Defines an Object?
Exercises
Chapter 7: Scripts and HTML Documents
Connecting Scripts to Documents
JavaScript Statements
When Script Statements Execute
Viewing Script Errors
Scripting versus Programming
Exercises
Chapter 8: Programming Fundamentals, Part I
What Language Is This?
Working with Information
Variables
Expressions and Evaluation
Data Type Conversions
Operators
Exercises
Chapter 9: Programming Fundamentals, Part II
Decisions and Loops
Control Structures
Repeat Loops
Functions
Curly Braces
Arrays
Exercises
Chapter 10: Window and Document Objects
Top-Level Objects
The window Object
window Properties and Methods
The location Object
The navigator Object
The document Object
Exercises
Chapter 11: Forms and Form Elements
The Form object
Form Controls as Objects
Passing Elements to Functions with this
Submitting and Prevalidating Forms
Exercises
Chapter 12: Strings, Math, and Dates
Core Language Objects
String Objects
The Math Object
The Date Object
Date Calculations
Exercises
Chapter 13: Scripting Frames and Multiple Windows
Frames: Parents and Children
References Among Family Members
Frame-Scripting Tips
About iframe Elements
Highlighting Footnotes: A Frameset Scripting Example
References for Multiple Windows
Exercises
Chapter 14: Images and Dynamic HTML
The Image Object
Rollovers Without Scripts
The javascript: Pseudo-URL
Popular Dynamic HTML Techniques
Exercises
Part III: JavaScript Core Language Reference
Chapter 15: The String Object
String and Number Data Types
String Object
String Utility Functions
URL String Encoding and Decoding
Chapter 16: The Math, Number, and Boolean Objects
Numbers in JavaScript
Math Object
Number Object
Boolean Object
Chapter 17: The Date Object
Time Zones and GMT
The Date Object
Validating Date Entries in Forms
Chapter 18: The Array Object
Structured Data
Creating an Empty Array
Populating an Array
JavaScript Array Creation Enhancements
Deleting Array Entries
Parallel Arrays
Multidimensional Arrays
Simulating a Hash Table
Array Object
Array Comprehensions
Destructuring Assignment
Compatibility with Older Browsers
Chapter 19: JSON—Native JavaScript Object Notation
How JSON Works
Sending and Receiving JSON Data
JSON Object
Security Concerns
Chapter 20: E4X—Native XML Processing
XML
ECMAScript for XML (E4X)
Chapter 21: Control Structures and Exception Handling
If and If…Else Decisions
Conditional Expressions
The switch Statement
Repeat (for) Loops
The while Loop
The do-while Loop
Looping through Properties (for-in)
The with Statement
Labeled Statements
Exception Handling
Using try-catch-finally Constructions
Throwing Exceptions
Error Object
Chapter 22: JavaScript Operators
Operator Categories
Comparison Operators
Connubial Operators
Miscellaneous Operators
Operator Precedence
Chapter 23: Function Objects and Custom Objects
Function Object
Function Application Notes
Creating Your Own Objects with Object-Oriented JavaScript
Object-Oriented Concepts
Object Object
Chapter 24: Global Functions and Statements
Functions
Statements
WinIE Objects
Part IV: Document Objects Reference
Chapter 25: Document Object Model Essentials
The Object Model Hierarchy
How Document Objects Are Born
Object Properties
Object Methods
Object Event Handlers
Object Model Smorgasbord
Basic Object Model
Basic Object Model Plus Images
Navigator 4–Only Extensions
Internet Explorer 4+ Extensions
Internet Explorer 5+ Extensions
The W3C DOM
Chapter 26: Generic HTML Element Objects
Generic Objects
Chapter 27: Window and Frame Objects
Window Terminology
Frames
window Object
frameset Element Object
iframe Element Object
popup Object
Chapter 28: Location and History Objects
location Object
history Object
Chapter 29: Document and Body Objects
document Object
body Element Object
TreeWalker Object
Chapter 30: Link and Anchor Objects
Anchor, Link, and a Element Objects
Chapter 31: Image, Area, Map, and Canvas Objects
Image and img Element Objects
area Element Object
map Element Object
canvas Element Object
Chapter 32: Event Objects
Why “Events”?
Event Propagation
Dueling Event Models
Event Types
NN6+/Moz event Object
Part V: Appendixes
Appendix A: JavaScript and Browser Objects Quick Reference
Appendix B: What's on the CD-ROM
Index
Advertisement
Bonus Chapters on the CD-ROM
Part VI: Document Objects Reference (continued)
Chapter 33: Body Text Objects
blockquote and q Element Objects
br Element Object
font Element Object
h1…h6 Element Objects
hr Element Object
label Element Object
marquee Element Object
Range Object
selection Object
Text and TextNode Objects
TextRange Object
TextRectangle Object
Chapter 34: The Form and Related Objects
The Form in the Object Hierarchy
form Object
fieldset and legend Element Objects
label Element Object
Scripting and Web Forms 2.0
Chapter 35: Button Objects
The button Element Object, and the Button, Submit, and Reset Input Objects
checkbox Input Object
radio Input Object
image Input Object
Chapter 36: Text-Related Form Objects
Text Input Object
password Input Object
hidden Input Object
textarea Element Object
Chapter 37: Select, Option, and FileUpload Objects
select Element Object
option Element Object
optgroup Element Object
file Input Element Object
Chapter 38: Style Sheet and Style Objects
Making Sense of the Object Names
Imported Style Sheets
Reading Style Properties
style Element Object
styleSheet Object
cssRule and rule Objects
currentStyle, runtimeStyle, and style Objects
filter Object
Chapter 39: Ajax, E4X, and XML
Elements and Nodes
xml Element Object
XMLHttpRequest Object
ECMAScript for XML (E4X)
Chapter 40: HTML Directive Objects
HTML Element Object
head Element Object
base Element Object
link Element Object
meta Element Object
script Element Object
title Element Object
Chapter 41: Table and List Objects
The Table Object Family Hierarchy
table Element Object
tbody, tfoot, and thead Element Objects
caption Element Object
col and colgroup Element Objects
tr Element Object
td and th Element Objects
ol Element Object
ul Element Object
li Element Object
dl, dt, and dd Element Objects
dir and menu Element Objects
Chapter 42: The Navigator and Other Environment Objects
clientInformation Object (IE4+) and navigator Object (All)
mimeType Object
plugin Object
Looking for mime Types and Plug-Ins
screen Object
userProfile Object
Chapter 43: Positioned Objects
What Is a Layer?
Positioned Elements in the Modern DOM
Chapter 44: Embedded Objects
applet Element Object
object Element Object
embed Element Object
The Odd Case of the param Element
Chapter 45: The Regular Expression and RegExp Objects
Regular Expressions and Patterns
Language Basics
Object Relationships
Using Regular Expressions
Regular Expression Object
RegExp Object
Part VII: More JavaScript Programming
Chapter 46: Data-Entry Validation
Real-Time Versus Batch Validation
Designing Filters
Building a Library of Filter Functions
Combining Validation Functions
Date and Time Validation
An Industrial-Strength Validation Solution
Plan for Data Validation
Chapter 47: Scripting Java Applets and Plug-Ins
NPAPI Overview
Why Control Java Applets?
A Little Java
Scripting Applets in Real Life
Applet-to-Script Communication
Scripting Plug-Ins
Scripting Java Classes Directly
Chapter 48: Debugging Scripts
Syntax versus Runtime Errors
Error Message Notification
Error Message Details
Warnings in Mozilla's Console
Sniffing Out Problems
Debugging Tools
A Simple Trace Utility
Browser Crashes
Preventing Problems
Testing Your Masterpiece
Chapter 49: Security and Netscape Signed Scripts
Battening Down the Hatches
When Worlds Collide
The Java Sandbox
Security Policies
The Same Origin Policy
The Netscape Signed Script Policy
The Digital Certificate
Signing Scripts
Accessing Protected Properties and Methods
Chapter 50: Cross-Browser Dynamic HTML Issues
What Is DHTML?
Striving for Compatibility
Working Around Incompatibilities
A DHTML API Example
Chapter 51: Internet Explorer Behaviors
Style Sheets for Scripts
Embedding Behavior Components
Component Structure
Behavior Examples
For More Information
Part VIII: Applications
Chapter 52: Application: Tables and Calendars
About the Calendars
Static Tables
Dynamic Tables
Hybrids
Dynamic HTML Tables
Further Thoughts
Chapter 53: Application: A Lookup Table
A Server-Less Database
The Database
The Implementation Plan
The Code
Further Thoughts
Chapter 54: Application: A Poor Man's Order Form
Defining the Task
The Form Design
Form HTML and Scripting
Further Thoughts
Chapter 55: Application: Outline-Style Table of Contents
The Implementation Plan
The Code
An Ajax (XML) Outline
Further Thoughts
Chapter 56: Application: Calculations and Graphics
The Calculation
User Interface Ideas
The Code
Further Thoughts
Chapter 57: Application: Intelligent “Updated” Flags
The Cookie Conundrum
Time's Not on Your Side
The Application
The Code
Further Thoughts
Chapter 58: Application: Decision Helper
The Application
The Design
The Files
The Code
Further Thoughts
Chapter 59: Application: Cross-Browser DHTML Map Puzzle
The Puzzle Design
Implementation Details
Further Thoughts
Chapter 60: Application: Transforming XML Data
Application Overview
Implementation Plan
The Code
Further Thoughts
Chapter 61: Application: Creating Custom Google Maps
A Google Maps Primer
Google Maps Customization Basics
Designing a Google Maps Mashup
Developing a Custom Map Document
Hacking Together a Custom Google Map
Further Thoughts
Part IX: Appendixes (continued)
Appendix C: JavaScript Reserved Words
Appendix D: Answers to Tutorial Exercises
Appendix E: JavaScript and DOM Internet Resources
Wiley Publishing, Inc. End-User License Agreement
Praise for 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 beginning programmer can understand it.”
—Jason Hensley, Director of Internet Services, NetVoice, Inc.
“Goodman is always great at delivering clear and concise technical books!”
—Dwayne King, Chief Technology Officer, White Horse
“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
JavaScript® Bible, Seventh Edition
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-52691-0
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 Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
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 web site 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 web site may provide or recommendations it may make. Further, readers should be aware that Internet web sites 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 please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Library of Congress Control Number: 2010923547
Trademarks: Wiley and the Wiley logo 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 Oracle America, Inc. 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.
To Tanya, with whom I share this loving orbit with Briar and Callum in our own cozy Klemperer rosette.
— Paul Novitski
To my husband, Edward, whose love, support, and encouragement kept me going through this and all my adventures, and to the memory of my parents who inspired me to step out in faith.
— Tia Gustaff Rayl
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 on and expert teacher of computer scripting languages. His writing style and pedagogy continue to earn praise from readers and teachers around the world.
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 writing 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 entertainment company specializing in unusual games, toys, and interactive products.
Paul Novitski has been writing software as a freelance programmer since 1981. He once taught himself BASIC in order to write a machine language disassembler so that he could lovingly hack Wang's OIS microcode. He has focused on internet programming since the late '90s. His company, Juniper Webcraft, produces HTML-strict websites featuring accessible, semantic markup, separation of development layers, and intuitive user interfaces. He knows the righteousness of elegant code, the poignancy of living on the bleeding edge of wilderness, the sweet melancholy of mbira music, and the scorching joy of raising twin boys.
Tia Gustaff Rayl is a consultant who does development and training in database and Web technologies. Most recently she has published courseware for XHTML, CSS, JavaScript, and SQL. It comes as no surprise to those who know her that she began her software career with degrees in English and Education from the University of Florida. As is usual for most newcomers to the field, her introduction to computing was maintaining software. She went on to a long-standing career in the software industry in full life cycle system, application, and database development; project management; and training for PC and mainframe environments. In the mid-nineties she worked on early Web-enabled database applications, adding JavaScript to her repertoire. She continues to take on development projects to maintain her code-slinging skills. If she had any spare time (and money) she would go on an around-the-world cruise with her husband and two dogs.
About the Technical Editor
Benjamin Schupak holds a master's degree in computer science and has more than 11 years of professional programming experience for large corporations and U.S. federal departments. He lives in the New York metro area and enjoys traveling.
Credits
Executive Editor
Carol Long
Project Editor
John Sleeva
Technical Editor
Benjamin Schupack
Production Editor
Rebecca Anderson
Editorial Director
Robyn B. Siesky
Editorial Manager
Mary Beth Wakefield
Marketing Manager
Ashley Zurcher
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Barry Pruett
Associate Publisher
Jim Minatel
Project Coordinator, Cover
Lynsey Stanford
Proofreaders
Maraya Cornell, Word One New York
Sheilah Ledwidge, Word One New York
Indexer
Robert Swanson
Cover Designer
Michael E. Trent
Cover Image
© Joyce Haughey
Acknowledgments
My gratitude for being given the opportunity and the latitude to work on this immense tome extends to Carol Long of Wiley, editor John Sleeva, Carole Jelen at Waterside Productions, Julian Hall, my partner in crime at Juniper Webcraft, and, above all, my sweet, loving, supportive, and nearly homicidal spouse Tanya Wright, all of them long-suffering and all to be commended for not actually throttling me in the course of this overlong birthing. The solid foundation of research and explication established by Danny Goodman and his past collaborators in previous editions is awesome and I am humbled to have been able to help move this great body of knowledge forward to the next step. Tia Gustaff Rayl, who with wings spread and sparks flying rode in to the rescue, has been a kick in the pants to work with; she's smart and funny, but more than that she is gifted with the precise serendipity and good taste to share a birthday with me.
–Paul Novitski
I have been blessed with the support of many people who have reviewed my work and encouraged me along the way. I could never have done any of this without the devoted support of my husband, Edward. I love him without cease and thank God for bringing him into my life. I have been blessed by the remarkable patience of an incredibly tolerant immediate and extended family, as well as amused friends, who put up with my “Hi, I love you. Don't talk to me right now.” way of answering the phone and greeting visitors at the door. My husband, family and friends are the ones who sacrificed the most for this book. Thank you all. I want to thank Paul for being great to work with and for his wry sense of humor which left me on the floor laughing just when I most needed a lift. I want to thank my editor, John Sleeva, who with great patience and humor guided me through the maze of the publishing world. I also want to thank Rebecca Anderson and Maraya Cornell for forcing me to be a better writer. Finally, I want to thank Miss Bigelow, my 11th and 12th grade English teacher, who instilled within me a great respect and love for the written word.
–Tia Gustaff Rayl
Introduction
This seventh edition of the JavaScript Bible represents knowledge and experience accumulated over fifteen years of daily work in JavaScript and a constant monitoring of newsgroups for questions, problems, and challenges facing scripters at all levels. Our goal is to help you avoid the same frustration and head-scratching we and others have experienced through multiple generations of scriptable browsers.
While the earliest editions of this book focused on the then-predominant Netscape Navigator browser, the browser market share landscape has changed through the years. For many years, Microsoft took a strong lead with its Internet Explorer, but more recently, other browsers that support industry standards are finding homes on users' computers. The situation still leaves an age-old dilemma for content developers: designing scripted content that functions equally well in both standards-compliant and proprietary environments. The job of a book claiming to be the “bible” is not only to present both the standard and proprietary details when they diverge, but also to show you how to write scripts that blend the two so that they work on the wide array of browsers visiting your sites or web applications. Empowering you to design and write good scripts is our passion, regardless of browser. It's true that our bias is toward industry standards, but not to the exclusion of proprietary features that may be necessary to get your content and scripting ideas flowing equally well on today's and tomorrow's browsers.
Organization and Features of This Edition
Like the previous three editions of the JavaScript Bible, this seventh edition contains far more information than can be printed and bound into a single volume. The complete contents can be found in the electronic version of this book (in PDF form) on the CD-ROM that accompanies the book. This edition is structured in such a way as to supply the most commonly needed information in its entirety in the printed portion of the book. Content that you use to learn the fundamentals of JavaScript and reference frequently are at your fingertips in the printed version, while chapters with more advanced content are in the searchable electronic version on the CD-ROM. Here are some details about the book's structure.
Part I: Getting Started with JavaScript
Part I of the book begins with a chapter that shows how JavaScript compares with Java and discusses its role within the rest of the World Wide Web. The web browser and scripting world have undergone significant changes since JavaScript first arrived on the scene. That's why Chapter 2 is devoted to addressing challenges facing scripters who must develop applications for both single- and cross-platform browser audiences amid rapidly changing standards efforts. Chapter 3 introduces some tools you can use to compose your pages and scripts, while Chapter 4 delves into the nitty-gritty of how to use JavaScript to run in a wide variety of browsers.
Part II: JavaScript Tutorial
All of Part II is handed over to a tutorial for newcomers to JavaScript. Ten lessons provide you with a gradual path through browser internals, basic programming skills, and genuine browser scripting, with an emphasis on industry standards as supported by most of the scriptable browsers in use today. Exercises follow at the end of each lesson to help reinforce what you just learned and challenge you to use your new knowledge (you'll find answers to the exercises in Appendix D, on the CD-ROM). The goal of the tutorial is to equip you with sufficient experience to start scripting simple pages right away while making it easier for you to understand the in-depth discussions and examples in the rest of the book.
Part III: JavaScript Core Language Reference
Reference information for the core JavaScript language fills Part III. In all reference chapters, a compatibility chart indicates the browser version that supports each object and object feature. Guide words near the tops of pages help you find a particular term quickly.
Part IV: Document Objects Reference
Part IV, the largest section of the book, provides in-depth coverage of the document object models as implemented in today's browsers, including the object used for modern Ajax applications. As with the core JavaScript reference chapters of Part III, these DOM chapters display browser compatibility charts for every object and object feature. One chapter in particular, Chapter 26, contains reference material that is shared by most of the remaining chapters of Part IV. To help you refer back to Chapter 26 from other chapters, a shaded tab along the outside edge of the page shows you at a glance where the chapter is located. Additional navigation aids include guide words near the tops of most pages to indicate which object and object feature is covered on the page. Note that the Objects Reference begun in Part IV of the book continues in Part IV on the CD, with an additional 13 chapters of reference material.
Part V: Appendixes
Appendix A offers a JavaScript and Browser Objects Quick Reference. Appendix B provides information about using the CD-ROM that comes with this book, which includes numerous bonus chapters and examples.
Part VI: Document Objects Reference (continued)
Beginning the portion of the book that resides only the accompanying CD, Part IV continues the document objects reference discussions that begin in Part IV by providing an additional 13 chapters of reference material.
Part VII: More JavaScript Programming
Chapters 46–51 discuss advanced JavaScript programming techniques, including data-entry validation, debugging, and security issues.
Part VIII: Applications
The final ten chapters of the book, available only on the CD-ROM, feature sample applications that cover the gamut from calendars to puzzles.
Part IX: Appendixes (continued)
The final three appendixes provide helpful reference information. These resources include a list of JavaScript reserved words in Appendix C, answers to Part II's tutorial exercises in Appendix D, and Internet resources in Appendix E.
CD-ROM
The CD-ROM is a gold mine of information. It begins with a PDF version of the entire contents of this seventh edition of the JavaScript Bible. This version includes bonus chapters covering:
Another treasure trove on the CD-ROM is the Listings folder where you'll find over 300 ready-to-run HTML documents that serve as examples of most of the document object model and JavaScript vocabulary words in Parts III and IV. All of the bonus chapter example listings are also included. You can run these examples with your JavaScript-enabled browser, but be sure to use the index.html page in the Listings folder as a gateway to running the listings. We could have provided you with humorous little sample code fragments out of context, but we think that seeing full-fledged HTML documents (simple though they may be) for employing these concepts is important. We encourage you to manually type the script listings from the tutorial (Part II) of this book. We believe you learn a lot, even by aping listings from the book, as you get used to the rhythms of typing scripts in documents.
Be sure to check out the Chapter 4 listing file called evaluator.html. Many segments of Parts III and IV invite you to try out an object model or language feature with the help of an interactive workbench, called The Evaluator—a JavaScript Bible exclusive! You see instant results and will quickly learn how the feature works.
The Quick Reference from Appendix A is in PDF format on the CD-ROM for you to print out and assemble as a handy reference, if desired. Adobe Reader is also included on the CD-ROM, in case you don't already have it.
Prerequisites to Learning JavaScript
Although this book doesn't demand that you have a great deal of programming experience behind you, the more web pages you've created with HTML, the easier you will find it to understand how JavaScript interacts with the familiar elements you normally place in your pages. Occasionally, you will need to modify HTML tags to take advantage of scripting. If you are familiar with those tags already, the JavaScript enhancements will be simple to digest.
To learn JavaScript, you won't need to know server scripting or how to pass information from a form to a server. The focus here is on client-side scripting, which operates independently of the server after the JavaScript-enhanced HTML page is fully loaded into the browser. However, we strongly believe that a public web page should be operational in the absence of JavaScript, so any dynamic functionality that looks up results or modifies the content of a page should interact with a server-side script fundamentally. After that foundation is laid, we add JavaScript to make a page faster, easier, or more fun. So although you don't need to know server-side scripting in order to learn JavaScript, for serious web work you should either learn a server-side scripting language such as PHP in addition to JavaScript or look for server-side programmers to complement your client-side scripting abilities.
The basic vocabulary of the current HTML standard should be part of your working knowledge. You should also be familiar with some of the latest document markup standards, such as XHTML and Cascading Style Sheets (CSS). Web searches for these terms will uncover numerous tutorials on the subjects.
If you've never programmed before
Don't be put off by the size of this book. JavaScript may not be the easiest language in the world to learn, but believe us, it's a far cry from having to learn a full programming language such as Java or C. Unlike developing a full-fledged monolithic application (such as the productivity programs you buy in stores), JavaScript lets you experiment by writing small snippets of program code to accomplish big things. The JavaScript interpreter built into every scriptable browser does a great deal of the technical work for you.
Programming, at its most basic level, consists of nothing more than writing a series of instructions for the computer to follow. We humans follow instructions all the time, even if we don't realize it. Traveling to a friend's house is a sequence of small instructions: Go three blocks that way; turn left here; turn right there. Amid these instructions are some decisions that we have to make: If the stoplight is red, then stop; if the light is green, then go; if the light is yellow, then floor it! (Just kidding.) Occasionally, we must repeat some operations several times (kind of like having to go around the block until a parking space opens up). A computer program not only contains the main sequence of steps, but it also anticipates what decisions or repetitions may be needed to accomplish the program's goal (such as how to handle the various states of a stoplight or what to do if someone just stole the parking spot you were aiming for).
The initial hurdle of learning to program is becoming comfortable with the way a programming language wants its words and numbers organized in these instructions. Such rules are called syntax, the same as in a living language. Computers aren't very forgiving if you don't communicate with them in the specific language they understand. When speaking to another human, you can flub a sentence's syntax and still have a good chance that the other person will understand you. Not so with computer programming languages. If the syntax isn't perfect (or at least within the language's range of knowledge), the computer has the brazenness to tell you that you have made a syntax error.
The best thing you can do is just accept the syntax errors you receive as learning experiences. Even experienced programmers make mistakes. Every syntax error you get—and every resolution of that error made by rewriting the wayward statement—adds to your knowledge of the language.
If you've done a little programming before
Programming experience in a procedural language, such as BASIC, may actually be a hindrance rather than a help to learning JavaScript. Although you may have an appreciation for precision in syntax, the overall concept of how a program fits into the world is probably radically different from JavaScript's role. Part of this has to do with the typical tasks a script performs (carrying out a very specific task in response to user action within a web page), but a large part also has to do with the nature of object-oriented programming.
If you've programmed in C before
In a typical procedural program, the programmer is responsible for everything that appears on the screen and everything that happens under the hood. When the program first runs, a great deal of code is dedicated to setting up the visual environment. Perhaps the screen contains several text entry fields or clickable buttons. To determine which button a user clicks, the program examines the coordinates of the click and compares those coordinates against a list of all button coordinates on the screen. Program execution then branches out to perform the instructions reserved for clicking in that space.
Object-oriented programming is almost the inverse of that process. A button is considered an object—something tangible. An object has properties, such as its label, size, alignment, and so on. An object may also contain a script. At the same time, the system software and browser, working together, can send a message to an object—depending on what the user does—to trigger the script. For example, if a user clicks in a text entry field, the system/browser tells the field that somebody has clicked there (that is, has set the focus to that field), giving the field the task of deciding what to do about it. That's where the script comes in. The script is connected to the field, and it contains the instructions that the field carries out after the user activates it. Another set of instructions may control what happens when the user types an entry and tabs or clicks out of the field, thereby changing the content of the field.
Some of the scripts you write may seem to be procedural in construction: They contain a simple list of instructions that are carried out in order. But when dealing with data from form elements, these instructions work with the object-based nature of JavaScript. The form is an object; each radio button or text field is an object as well. The script then acts on the properties of those objects to get some work done.
Making the transition from procedural to object-oriented programming may be the most difficult challenge for you. But when the concept clicks—a long, pensive walk might help—so many light bulbs will go on inside your head that you'll think you might glow in the dark. From then on, object orientation will seem to be the only sensible way to program.
By borrowing syntax from Java (which, in turn, is derived from C and C++), JavaScript shares many syntactical characteristics with C. Programmers familiar with C will feel right at home. Operator symbols, conditional structures, and repeat loops follow very much in the C tradition. You will be less concerned about data types in JavaScript than you are in C. In JavaScript, a variable is not restricted to any particular data type.
With so much of JavaScript's syntax familiar to you, you will be able to concentrate on document object model concepts, which may be entirely new to you. You will still need a good grounding in HTML to put your expertise to work in JavaScript.
If you've programmed in Java before
Despite the similarity in their names, the two languages share only surface aspects: loop and conditional constructions, C-like “dot” object references, curly braces for grouping statements, several keywords, and a few other attributes. Variable declarations, however, are quite different, because JavaScript is a loosely typed language. A variable can contain an integer value in one statement and a string in the next (though we're not saying that this is good style). What Java refers to as methods, JavaScript calls methods (when associated with a predefined object) or functions (for scripter-defined actions). JavaScript methods and functions may return values of any type without having to state the data type ahead of time.
Perhaps the most important Java concepts to suppress when writing JavaScript are the object-oriented notions of classes, inheritance, instantiation, and message passing. These aspects are simply non-issues when scripting. At the same time, however, JavaScript's designers knew that you'd have some hard-to-break habits. For example, although JavaScript does not require a semicolon at the end of each statement line, if you type one in your JavaScript source code, the JavaScript interpreter won't balk.
If you've written scripts (or macros) before
Experience with writing scripts in other authoring tools or macros in productivity programs is helpful for grasping a number of JavaScript's concepts. Perhaps the most important concept is the idea of combining a handful of statements to perform a specific task on some data. For example, you can write a macro in Microsoft Excel that performs a data transformation on daily figures that come in from a corporate financial report on another computer. The macro is built into the Macro menu, and you run it by choosing that menu item whenever a new set of figures arrives.
Some modern programming environments, such as Visual Basic, resemble scripting environments in some ways. They present the programmer with an interface builder, which does most of the work of displaying screen objects with which the user will interact. A big part of the programmer's job is to write little bits of code that are executed when a user interacts with those objects. A great deal of the scripting you will do with JavaScript matches that pattern exactly. In fact, those environments resemble the scriptable browser environment in another way: They provide a finite set of predefined objects that have fixed sets of properties and behaviors. This predictability makes learning the entire environment and planning an application easier to accomplish.
Formatting and Naming Conventions
The script listings and words in this book are presented in a monospace font to set them apart from the rest of the text. Because of restrictions in page width, lines of script listings may, from time to time, break unnaturally. In such cases, the remainder of the script appears in the following line, flush with the left margin of the listing, just as it would appear in a text editor with word wrapping turned on. If these line breaks cause you problems when you type a script listing into a document yourself, we encourage you to access the corresponding listing on the CD-ROM to see how it should look when you type it.
As soon as you reach Part III of this book, you won't likely go for more than a page before reading about an object model or language feature that requires a specific minimum version of one browser or another. To make it easier to spot in the text when a particular browser and browser version is required, most browser references consist of an abbreviation and a version number. For example, WinIE5 means Internet Explorer 5 for Windows; NN4 means Netscape Navigator 4 for any operating system; Moz stands for the modern Mozilla browser (from which Firefox, Netscape 6 or later, and Camino are derived); and Safari is Apple's own browser for Mac OS X. If a feature is introduced with a particular version of browser and is supported in subsequent versions, a plus symbol (+) follows the number. For example, a feature marked WinIE5.5+ indicates that Internet Explorer 5.5 for Windows is required at a minimum, but the feature is also available in WinIE8 and probably future WinIE versions. If a feature was implemented in the first release of a modern browser, a plus symbol immediately follows the browser family name, such as Moz+ for all Mozilla-based browsers. Occasionally, a feature or some highlighted behavior applies to only one browser. For example, a feature marked NN4 means that it works only in Netscape Navigator 4.x. A minus sign (e.g., WinIE-) means that the browser does not support the item being discussed.
The format of HTML markup in this edition follows HTML5 coding conventions, but also adheres to many XHTML standards such as all-lowercase tag and attribute names.
Note | Tip | Note, Tip, Caution, and Cross-Reference icons occasionally appear in the book to flag important points or suggest where to find more information. |
Caution | Cross Reference |
Part I
Getting Started with Javascript
In This Part
Chapter 1 JavaScript's Role in the World Wide Web and Beyond
Chapter 2 Developing a Scripting Strategy
Chapter 3 Selecting and Using Your Tools
Chapter 4 JavaScript Essentials