THE BOOK of
™
JAVASCRIPT
2ND EDITION
A PRACTICAL GUIDE TO INTERACTIVE
WEB PAGES
by thau!
San Francisco
®
THE BOOK OF JAVASCRIPT, 2ND EDITION. Copyright © 2007 by Dave Thau.
First edition © 2000 by Dave Thau.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior
written permission of the copyright owner and the publisher.
10 09 08 07 06 1 2 3 4 5 6 7 8 9
ISBN-10: 1-59327-106-9
ISBN-13: 978-1-59327-106-0
Publisher: William Pollock
Associate Production Editor: Christina Samuell
Cover and Interior Design: Octopod Studios
Developmental Editors: Jim Compton, William Pollock, and Riley Hoffman
Technical Reviewer: Luke Knowland
Copyeditor: Publication Services, Inc.
Compositors: Riley Hoffman and Megan Dunchak
Proofreader: Stephanie Provines
Indexer: Nancy Guenther
For information on book distributors or translations, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
555 De Haro Street, Suite 250, San Francisco, CA 94107
phone: 415.863.9900; fax: 415.863.9950; ; www.nostarch.com
Chapter 2: Using Variables and Built-in Functions to
Update Your Web Pages Automatically 15
Chapter 3: Giving the Browsers What They Want 33
Chapter 4: Working with Rollovers 51
Chapter 5: Opening and Manipulating Windows 67
Chapter 6: Writing Your Own JavaScript Functions 83
Chapter 7: Providing and Receiving Information with Forms 99
Chapter 8: Keeping Track of Information with Arrays and Loops 123
Chapter 9: Timing Events 147
Chapter 10: Using Frames and Image Maps 169
Chapter 11: Validating Forms, Massaging Strings, and
Working with Server-Side Programs 191
Chapter 12: Saving Visitor Information with Cookies 215
viii Brief Contents
Chapter 13: Dynamic HTML 233
Chapter 14: Ajax Basics 261
Chapter 15: XML in JavaScript and Ajax 279
Chapter 16: Server-Side Ajax 299
Chapter 17: Putting It All Together in a Shared To Do List 331
Chapter 18: Debugging JavaScript and Ajax 363
Appendix A: Answers to Assignments 381
Appendix B: Resources 405
Appendix C: Reference to JavaScript Objects and Functions 411
Appendix D: Chapter 15’s Italian Translator and Chapter 17’s To Do List Application 455
Index 469
CONTENTS IN DETAIL
FOREWORD by Luke Knowland xxi
FOREWORD TO THE FIRST EDITION by Nadav Savio xxiii
ACKNOWLEDGMENTS xxv
INTRODUCTION xxvii
Write Here Right Now: Displaying Results 19
Line-by-Line Analysis of Figure 2-4 20
Strings 20
Line-by-Line Analysis of Figure 2-6 21
x Contents in Detail
More About Functions 21
alert() 22
Line-by-Line Analysis of Figure 2-9 23
prompt() 24
Parameters 25
Writing the Date to Your Web Page 26
Built-in Date Functions 26
Date and Time Methods 26
Code for Writing the Date and Time 27
Line-by-Line Analysis of Figure 2-12 29
How the European Space Agency Writes the Date to Its Page 30
Summary 31
Assignment 31
3
GIVING THE BROWSERS WHAT THEY WANT 33
A Real-World Example of Browser Detection 34
Browser Detection Methods 35
Quick-but-Rough Browser Detection 35
More Accurate Browser Detection 36
Redirecting Visitors to Other Pages 37
if-then Statements 38
Boolean Expressions 38
Nesting 40
if-then-else Statements 40
if-then-else-if Statements 41
Real-World Examples of Opening Windows to Further Information 68
Working with Windows as Objects 69
Opening Windows 69
Manipulating the Appearance of New Windows 70
Some Browsers and Computers Open Windows Differently 72
Closing Windows 72
Using the Right Name: How Windows See Themselves and Each Other 73
Moving Windows to the Front or Back of the Screen 74
Window Properties 74
The status Property 74
The opener Property 75
More Window Methods 77
Resizing Windows 77
Moving Windows 77
Summary 80
Assignment 80
6
WRITING YOUR OWN JAVASCRIPT FUNCTIONS 83
Functions as Shortcuts 84
Basic Structure of JavaScript Functions 84
Naming Your Functions 85
Parentheses and Curly Brackets 85
An Example of a Simple Function 85
Writing Flexible Functions 86
Using Parameters 87
Line-by-Line Analysis of Figure 6-4 88
Using More Than One Parameter 90
Getting Information from Functions 91
Line-by-Line Analysis of Figure 6-9 92
Dealing with Y2K 93
How the Doctors Without Borders Pull-Down Navigation Tool Works 120
Summary 120
Assignment 121
8
KEEPING TRACK OF INFORMATION WITH
ARRAYS AND LOOPS 123
Real-World Examples of Arrays 123
JavaScript’s Built-In Arrays 124
Figuring Out How Many Items an Array Contains 126
Going Through Arrays 126
while Loops 128
while Loops and Arrays 129
Going Off the Deep End 130
Using array.length in Your Loop 131
An Incremental Shortcut 131
Beware of Infinite Loops 131
for Loops 132
How AntWeb Checks Off All the Checkboxes 133
Line-by-Line Analysis of Figure 8-11 133
Creating Your Own Arrays 134
Line-by-Line Analysis of Figure 8-12 135
How the Book of JavaScript Tip Box Works 136
Checking for Blank Statements 137
Checking the Last Element in the Array 137
Contents in Detail xiii
Testing the Limits of Arrays 137
The startScroll() Function 138
A Streamlined Version 139
Loops Can Nest 140
Creating Arrays As You Go Along 140
Summary 167
Assignment 167
10
USING FRAMES AND IMAGE MAPS 169
A Real-World Example of Frames and Image Maps 170
Frames 170
Frame Basics 170
Frames and JavaScript 172
Frames and Image Swaps 174
Changing the Contents of Two Frames at Once 176
Frames Inside Frames 177
JavaScript and Frames Inside Frames 179
xiv Contents in Detail
Frame Busting 179
Using Frames to Store Information 181
Line-by-Line Analysis of Figure 10-15 183
Image Maps 184
Image Map Basics 185
Image Maps and JavaScript 186
How Salon’s Bug-Eating Script Works 186
Salon’s Nested Frames 188
Salon’s Image Map 188
The changeMe() Function 188
Summary 189
Assignment 190
11
VALIDATING FORMS, MASSAGING STRINGS,
AND WORKING WITH SERVER-SIDE PROGRAMS 191
A Real-World Example of Form Validation 192
Making Sure a Visitor Has Filled Out a Form Element 192
Contents in Detail xv
13
DYNAMIC HTML 233
Real-World Examples of DHTML 234
CSS Basics 234
The <div> Tag 235
Positioning a div with CSS 235
Hiding a div 237
Layering divs 237
JavaScript and DHTML 238
Making divs Move 239
Using setTimeout() and clearTimeout() to Animate a Page 239
Line-by-Line Analysis of Figure 13-10 240
Changing the Contents of a div 241
spans and getElementsByTagName() 242
Advanced DOM Techniques 244
W3C DOM Overview 245
Creating and Adding Elements Using the W3C DOM 245
Adding Text to an Element 246
Adding Elements in the Middle of a Page and Removing Elements 247
Additional DOM Details 248
Manipulating a Page Using the DOM 250
Fancy Event Handling 250
The event Object 250
Adding Event Handlers Using JavaScript 254
Drop-Down Menus 257
Line-by-Line Analysis of Figure 13-23 259
The Borders 259
Summary 259
Assignment 260
Summary 276
Assignment 277
15
XML IN JAVASCRIPT AND AJAX 279
A Real-World Example of Ajax and XML 280
Google Suggest 281
XML—the Extensible Markup Language 282
The Rules of XML 283
The XML Header 283
XML Elements 284
XML Attributes 284
Illegal XML Characters 284
XML Documents Have a Single Root Element 285
Final Comments About the XML Format 285
Processing XML 285
Line-by-Line Analysis of Figure 15-6 287
Internet Explorer, responseXML, and Client-Side Ajax 291
Problems with White Space in XML 291
Creating a Suggest Application for Translation 292
Finding the Translations 294
Displaying the Results 295
Summary 296
Assignment 297
16
SERVER-SIDE AJAX 299
Real-World Examples of Server-Side Ajax 300
The Power of Webservers 301
A Server-Side Programming Language 303
PHP Basics 304
Sending Simple Input to PHP with a GET Request 305
Features of the To Do List Application 332
To Do List Data Files 334
userInfo.xml 334
To Do List File 335
To Do List Server Side 336
The To Do List Client Side, Part 1: The HTML 337
The To Do List Client Side, Part 2: The JavaScript 338
The Function Road Map 339
Logging In and Out 340
Functions Related to Logging In 341
Helper Functions 343
Displaying Available Lists 346
Displaying a Specific List 349
Processing Changes to a List 352
Limitations on Manipulating XML Documents 356
Adding a New Item 357
A Few Closing Notes 359
Client-Side or Server-Side Code? 359
Security Issues 359
Summary 361
Assignment 361
xviii Contents in Detail
18
DEBUGGING JAVASCRIPT AND AJAX 363
Good Coding Practices 364
Starting with Comments 364
Filling In the Code 365
Avoiding Common Mistakes 365
Use a Consistent Naming Convention 365
Avoid Reserved Words 366
index.html 390
assignment-nav.html 390
blank.html 391
Chapter 11 391
index.html 391
assignment-nav.html 392
blank.html 394
Chapter 12 394
Chapter 13 395
Contents in Detail xix
Chapter 14 397
addressBook.xml 397
index.html 397
Chapter 17 399
Join Functions 400
Giving a User Access to Your To Do List 402
B
RESOURCES 405
Tutorials 405
HTML Tutorials 406
Cascading Style Sheets Tutorials 406
Advanced Topics in JavaScript 406
Ajax Tutorials 407
Example JavaScript and Ajax Code 407
Good Ajax Websites 407
Ajax Frameworks 408
JavaScript 408
PHP 409
Java 409
.NET 410
Navigator 433
Number 434
Option 435
parseInt() 436
parseFloat() 436
Password 436
prompt() 438
Radio 438
Reset 439
Screen 439
Select 439
setInterval() 440
setTimeout() 441
String 441
Style 445
Submit 446
Text 446
Textarea 447
this 448
unescape() 448
var 448
window 448
XMLHttpRequest and ActiveXObject("Microsoft.XMLHTTP") 454
D
CHAPTER 15’S ITALIAN TRANSLATOR
AND CHAPTER 17’S TO DO LIST APPLICATION 455
Chapter 15’s Italian Translator 455
Chapter 17’s To Do List Application 457
todo.html 457
readXMLFile.php 467
ingly) Dave manages to break down what Ajax is and what it isn’t, explains
when it makes sense to use it, and shows you how to do it.
If you’re new to JavaScript, you win—you couldn’t ask for a better person
to teach you how to program. If you’re an old hat at JavaScript and you’re
looking for a refresher course or wondering how to take advantage of Ajax,
you win too.
Happy coding!
Luke Knowland
Interaction Designer, Six Apart
San Francisco
FOREWORD TO THE
FIRST EDITION
I learned JavaScript completely on my own. There was
no one to tell me about “event handlers” or how to set
cookies. No one even explained what a variable is, let
alone the best ways to name them. Of course I had reference books, but
they were intimidating tomes, full of cryptic lists and tables, written by
programmers for programmers.
David Thau is a remarkable combination of natural teacher and seasoned
programmer. As a result, The Book of JavaScript not only teaches JavaScript
thoroughly and enjoyably in a friendly, unintimidating tone, but it teaches
programming as elegantly as any book I’ve seen. In fact, I’ve always thought
of this as Thau’s ulterior motive—he pretends he’s just showing you how to
make a rollover or validate the text in an HTML form, but before you know
it you’ve learned how to code!
Perhaps the most telling thing I can say is that, reading this book, I can’t
help but wish I was learning JavaScript for the first time. If you are, then con-
sider yourself lucky to have Thau as a teacher. You couldn’t do better.
Happy JavaScripting!
Nadav Savio