Contents at a Glance I Getting Started with JavaScript 1 An Overview of JavaScript 11 2 Creating Your First Scripts 17 II Programming Fundamentals 3 Understanding Variables 39 4 Working with Functions 51 5 Building JavaScript Expressions 71 6 Controlling Your Code I: Testing 101 7 Controlling Your Code II: Looping 111 8 Working with Objects 127 9 Handling Events 141 10 Working with Arrays 165 11 Interacting with the User 197 12 Debugging Your Code 207 III Basic Objects 13 Dealing with Dates and Times: The Date Object 223 14 Working with Numbers: The Math Object 243 15 Manipulating Text: The String Object 265 16 Controlling the Browser: The Navigator Object 297 IV Working with Browser Windows 17 Understanding the Window Object 319 18 Opening, Moving, and Sizing Windows 337 19 JavaScript Surfing: The Location and History Objects 361 20 Manipulating Frames 377 21 JavaScript Project: Setting Up a Password-Protected Page 405 VWorking with the Document Object 22 Understanding the Document Object 427 23 Programming Links, Anchors, and Image Maps 447 24 Working with Images and Mouseovers 467 25 Creating and Using Cookies 495 26 JavaScript Project: Creating a Navigation Tree 523 VI Working with Forms 27 Understanding the Form Object 549 28 Programming Form Fields 569 29 Performing Form Validation 605 30 JavaScript Project: Creating a Shopping Cart 637 VII Working with Dynamic HTML 31 A Brief Overview of Dynamic HTML 673 32 Version 5 DHTML: The W3C’s Document Object Model 683 33 Version 4 DHTML: Proprietary Object Models 721 34 Cross-Browser Solutions: Detection and Generic Functions 731 35 Cross-Browser DHTML Examples 769 VIII Appendixes A JavaScript Tools for Debugging Scripts 831 B JavaScript Reserved Words and Keywords 849 C Working with Regular Expressions 853 Index 873 Using JavaScript Paul McFedries 201 W. 103rd Street Indianapolis, Indiana 46290 Special Edition Using JavaScript Copyright © 2001 by Que All rights reserved. No part of this book shall be repro- duced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the pub- lisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for dam- ages resulting from the use of the information contained herein. International Standard Book Number: 0-7897-2576-2 Library of Congress Catalog Card Number: 2001087883 Printed in the United States of America First Printing: June 2001 04 03 02 01 4321 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capi- talized. Que cannot attest to the accuracy of this informa- tion. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information con- tained in this book. Acquisitions Editor Dean Miller Development Editor Sean Dixon Managing Editor Thomas F. Hayes Project Editor Heather McNeill Copy Editor Julie McNamee Indexer Tina Trettin Proofreader Harvey Stanbrough Technical Editor Jim O’Donnell Team Coordinator Cindy Teeters Interior Designer Ruth Harvey Cover Designer Dan Armstrong Ruth Harvey Page Layout Lizbeth Patterson Contents Introduction 1 What You Need to Know 3 How the Book Is Structured 3 Where’s the Code? 6 Conventions Used in This Book 6 I Getting Started with JavaScript 1 An Overview of JavaScript 11 JavaScript: Controlling the Machine 12 What Is a Programming Language? 12 Is JavaScript Hard to Learn? 14 What Can You Do with JavaScript? 14 What Can’t You Do with JavaScript? 15 Cross-Browser Concerns 16 2Creating Your First Scripts 17 What Do You Need to Get Started? 18 The Text Editor 18 The Browser 19 Basic Script Construction 20 The <script> Tag 20 Where Do You Put the Tag? 22 Example #1: Displaying a Message to the User 22 More JavaScript Examples 24 Example #2: Writing Data to the Page 24 Example #3: A JavaScript Function 26 Example #4: Handling a JavaScript Event 28 Adding Comments to Your Code 29 Creating External JavaScript Files 30 Debugging and Troubleshooting Script Problems 32 II Programming Fundamentals 3 Understanding Variables 39 What Is a Variable? 40 Declaring a Variable 40 Storing a Value in a Variable 41 Using Variables in Statements 42 Naming Variables: Rules and Best Practices 44 Rules for Naming Variables 44 Ideas for Good Variable Names 44 Understanding Literal Data Types 45 Working with Numeric Literals 46 Working with String Literals 47 Understand Boolean Literals 49 4Working with Functions 51 What Is a Function? 52 The Structure of a Function 52 Where Do You Put a Function? 53 Using a Function 54 Passing Values to Functions 56 Returning a Value from a Function 60 Understanding Local Versus Global Variables 61 Working with Local Scope 62 Working with Global Scope 64 Using Recursive Functions 65 Debugging and Troubleshooting Script Problems 68 Avoiding Infinite Recursion 68 5 Building JavaScript Expressions 71 What Is an Expression? 72 Understanding Expression Structure 72 Building Numeric Expressions 73 A Quick Look at the Arithmetic Operators 73 Using the Addition (+) Operator 74 Using the Increment (++) Operator 75 Using the Subtraction and Negation (-) Operators 76 Using the Decrement ( ) Operator 78 Using the Multiplication (*) Operator 79 Using the Division (/) Operator 79 Using the Modulus (%) Operator 80 Using the Arithmetic Assignment Operators 81 Building String Expressions 82 Building Comparison Expressions 84 The Comparison Operators 84 Using the Equal (==) Operator 85 Using the Not Equal (!=) Operator 85 Using the Greater Than (>) Operator 86 Using the Less Than (<) Operator 86 Using the Greater Than Or Equal (>=) Operator 86 Using the Less Than or Equal (<=) Operator 86 The Comparison Operators and Data Conversion 87 Using the Identity (===) Operator 88 Using the Non-Identity (!==) Operator 88 Special Edition Using JavaScript iv Using Strings in Comparison Expressions 88 Using the Conditional (?:) Operator 89 Building Logical Expressions 91 The Logical Operators 91 Using the AND (&&) Operator 91 Using the OR (||) Operator 92 Using the NOT (!) Operator 93 Advanced Notes On the && and || Operators 94 Understanding Operator Precedence 96 The Order of Precedence 96 Controlling the Order of Precedence 97 6 Controlling Your Code I: Testing 101 Using if() to Make True/False Decisions 102 Using if() else to Handle a false Result 103 Making Multiple Decisions 105 Using the AND (??) and OR (||) Operators 105 Nesting Multiple if() Statements 106 Using the switch() Statement 107 Debugging and Troubleshooting Script Problems 110 7 Controlling Your Code II: Looping 111 What Is Looping and Why Does Your Code Need It? 112 Using while() Loops 113 Using for() Loops 115 Using do while() Loops 118 Controlling Loop Execution: break and continue 120 Exiting a Loop: Using the break Statement 120 Bypassing Loop Statements: Using the continue Statement 123 Debugging and Troubleshooting Script Problems 124 8Working with Objects 127 What Is an Object? 128 The JavaScript Object Hierarchy 129 The Window Object and Its Hierarchy 129 Other Built-In JavaScript Objects 131 Manipulating Object Properties 132 Referencing a Property 132 Some Objects Are Properties 134 Changing the Value of a Property 134 Using for() in to Loop Through Object Properties 135 Working with Object Methods 137 Activating a Method 138 Using with() to Shorten Object Expressions 139 9 Handling Events 141 Understanding Events 142 Constructing Event Handlers 142 Step 1: Add the Event Handler Setup Attribute 142 Step 2: Set the Value of the Attribute 143 Setting Up Event Handlers as Object Properties 145 Using this to Refer to an Event’s Object 146 v Contents Using the JavaScript Events 147 Handling When an Object Gets and Loses the Input Focus 148 The Change Event: Handling Modified Form Data 152 Handling Keyboard Events 153 Handling Mouse Events 156 Debugging and Troubleshooting Script Problems 163 10 Working with Arrays 165 What Is an Array? 166 Declaring an Array 167 Populating an Array with Data 168 Declaring and Populating an Array at the Same Time 170 Using a Loop to Populate an Array 170 Using a Loop to Work with Array Data 172 Creating Multidimensional Arrays 173 Using the Array Object 176 The Array Object’s Properties 176 The Array Object’s Methods 178 Debugging and Troubleshooting Script Problems 189 11 Interacting with the User 197 Why Interact at All? 198 Displaying Messages Using the alert() Method 198 How the Alert Boxes Appear in Different Browsers 199 Asking Questions Using the confirm() Method 201 Getting Input Using the prompt() Method 202 How the Prompt Boxes Appear in Different Browsers 203 Debugging and Troubleshooting Script Problems 205 Don’t Overdo It 205 12 Debugging Your Code 207 What Is a Bug? 208 Understanding the Various Types of Errors 208 Syntax Errors 208 Runtime Errors 209 Logic Errors 209 A Debugging Strategy 210 Look for the Top 10 Most Common Errors 210 Display Expression Values 212 Display the Values of Object Properties 216 More Debugging Strategies 217 The Top 10 Most Common JavaScript Error Messages 217 III Basic Objects 13 Dealing with Dates and Times: The Date Object 223 Understanding JavaScript Dates 224 Arguments Used with the Date Object 224 Working with the Date Object 225 Specifying the Current Date and Time 225 Specifying Any Date and Time 225 Extracting Information About a Date 227 Converting getMonth() into a Month Name 230 Converting getDay() into a Day Name 232 Special Edition Using JavaScript vi Setting the Date 233 Determining the Day of the Week for Any Date 234 Performing Date Calculations 236 Determining a Person’s Age 236 Performing Complex Date Calculations 237 Calculating an Age In Weeks, Days, and So On 237 Calculating the Days Between Two Dates 239 Other Date Object Methods 240 14 Working with Numbers: The Math Object 243 How JavaScript Handles Numbers 244 A Quick Look at the Number Object 245 Converting Between Strings and Numbers 246 The parseInt() Function 247 The parseFloat() Function 247 The eval() Function 248 The Math Object 249 Properties of the Math Object 249 Methods of the Math Object 250 Rounding Numbers 251 Rounding a Number to a Specified Number of Decimals 252 Performing Financial Calculations 253 Generating Random Numbers 260 15 Manipulating Text: The String Object 265 Strings and the String Object 266 Determining the Length of a String 266 String Object Methods 268 Formatting Strings 268 Finding Substrings 271 Methods That Extract Substrings 274 A Few More String Object Methods 281 Programming a Library of Common String Functions 283 Extracting Characters from the Left: The left() Method 284 Extracting Characters from the Right: The right() Method 284 Tr imming Extra Spaces: The trim() Method 285 Converting a String to Title Case: The titleCase() Method 287 Replacing One Substring with Another 289 Formatting a Number with Thousands Separators 291 Padding a Number with Zeros 293 16 Controlling the Browser: The Navigator Object 297 About the Navigator Object 298 Determining the User’s Browser Information 304 Determining the Browser Name 304 Determining the Browser Version 305 Understanding the userAgent Property 307 Determining the Browser Name, Part 2 309 Determining the Operating System 311 Putting It All Together: The Browser Sniffer 313 vii Contents IV Working with Browser Windows 17 Understanding the Window Object 319 Revisiting the Window Object Hierarchy 320 Referencing the Window Object 321 Window Dimensions and the Screen Object 322 Displaying Messages In the Status Bar 325 Displaying a Custom Link Message 325 Setting Up a Default Status Bar Message 327 Working with JavaScript Timeouts and Intervals 328 Using a Timeout to Perform a Future Action Once 328 Using an Interval to Perform a Future Action Repeatedly 331 Emulating setInterval() with setTimeout() 332 Creating a Scrolling Status Bar Message 333 18 Opening, Moving, and Sizing Windows 337 Opening a Window 338 The JavaScript Way: The window.open() Method 338 The Simplest window.open() Method Syntax 338 Controlling the Size and Position of the New Window 341 Displaying Toolbars, Menu Bars and Other Window “Chrome” 344 Referencing the Page That Opened a Window 347 Closing a Window 349 Moving a Window 351 Moving a Window to a Specific Spot 351 Moving a Window by a Specified Amount 355 Resizing a Window 359 Resizing a Window to a Specific Size 359 Resizing a Window by a Specified Amount 360 19 JavaScript Surfing: The Location and History Objects 361 Surfing Under Script Control 362 Using the Location Property to Change the Displayed Page 362 Location Object Properties: 365 Surfing Using the Location Object’s Properties 365 Using search to Pass a Parameter to Another Web Page 369 Methods of the Location Object 372 Programmed Surfing with the History Object 374 Methods of the History Object 375 20 Manipulating Frames 377 Understanding Frame References 378 Parent-to-Child References 379 Child-to-Parent References 380 Child-to-Child References 381 Referencing Nested Frames 383 The top Property 391 Programming Frames 392 Loading a Page into a Frame 392 Updating Multiple Frames with One Link 393 Navigating to the Top and Bottom of a Frame 394 Special Edition Using JavaScript viii ”Deframing” a Page: Getting Out of Someone Else’s Frames 395 ”Reframing” a Page: Putting a Child Page Back Inside a Frameset 397 Working with Another Frame’s Variables and Functions 399 Synchronizing Frame Loading 401 21 JavaScript Project: Setting Up a Password- Protected Page 405 Web Page Security Issues 406 A First Attempt at Password Protection 406 Prompting for a Password 406 Converting the Password and Filename into Codes 408 The First Real Solution: A Trick for Hiding the Password 411 Trying Out the Trick 411 Making the Script a Bit More User- Friendly 412 Solving the “404 Not Found” Problem 413 Handling Multiple Users and Passwords 418 Debugging and Troubleshooting Script Problems 423 V Working with the Document Object 22 Understanding the Document Object 427 Structure of the Document Object 428 Properties of the Document Object 428 Changing Document Colors 430 Using Color Names 431 Using RGB Values 434 Methods of the Document Object 437 Writing Data to the Page 437 Writing to a Document at Startup 438 Writing Browser-Specific Code 440 Writing to a Document In Another Window 442 23 Programming Links and Anchors 447 Working with the Link Object 448 Using Functions in Place of URLs in a Link 448 Referencing a Link Object 449 Link Object Properties 449 Link Object Events 455 Working with the Anchor Object 462 Referencing an Anchor Object 462 Anchor Object Properties 462 24 Working with Images and Mouseovers 467 Working with the Image Object 468 Referencing an Image Object 468 Properties of the Image Object 469 Changing the Image Source 470 Cycling Through a Series of Images 470 Creating a “Running” Digital Clock 472 Preloading Images 475 Preloading Images for Animation 476 Loading an Image into a Custom-Sized Window 479 Handling Image Object Events 481 Creating Mouseover Effects 487 The Simplest Mouseover 487 Preloading Mouseover Images 490 Using a Text Link Mouseover to Change an Image 492 ix Contents 25 Creating and Using Cookies 495 Saving State: The Need for Truly Global Variables 496 What is a Cookie? 496 Advantages of Cookies 497 Disadvantages of Cookies 498 Setting Cookie Data 499 The Simplest Case: Setting the Cookie Name and Value 499 Getting the Cookie Value 500 Handling Multiple Cookies 501 Adding an Expiration Date 504 Specifying the Path 505 Setting Other Cookie Data 506 Handling All the Cookie Parameters 507 Deleting a Cookie 510 Advanced Cookie Operations 511 Storing Multiple Values in a Single Cookie 511 Encoding Cookie Values 513 Encrypting Cookie Values 516 Debugging and Troubleshooting Script Problems 520 Building a Stronger Key 520 26 JavaScript Project: Creating a Navigation Tree 523 The Need for Navigation 524 Stage 1: Designing and Creating the Menu Objects 525 Stage 2: Writing a Basic Menu 530 Stage 3: Expanding and Collapsing the Menu Items 534 Stage 3: Expanding and Collapsing the Menu Items 535 Stage 4: Adding Graphics and Other Interface Enhancements 538 VI Working with Forms 27 Understanding the Form Object 549 Structure of the Form Object 550 Referencing a Form Object 550 Form Object Properties 551 Understanding Form Fields 551 Referencing a Form Field 552 Common Form Field Properties 553 Looping Through Form Fields 554 Passing Form and Field Objects to a Function 555 Programming Buttons 556 Accepting or Rejecting a Submit 556 Accepting or Rejecting a Reset 559 Using a Button to Process Other Code 560 Forcing a Submit or Reset: The sub- mit() and reset() Methods 562 Restricting the Number of Form Submissions 564 28 Programming Form Fields 569 Now For Some Real Form Programming 570 Programming Text Fields 570 The Text Object 570 The Textarea Object 571 The Password Object 572 The FileUpload Object 572 The Hidden Object 573 Getting a Text Field Value 574 Setting a Text Field Value 576 A More Ambitious Example: A Mortgage Calculator 578 Making a Text Field Read-Only 582 Special Edition Using JavaScript x Programming Checkboxes 585 Getting the Checkbox State 586 Setting the Checkbox State 586 Using a Checkbox to Disable Form Fields 587 Controlling the Number of Activated Checkboxes 588 Programming Radio Buttons 590 Referencing Radio Buttons 591 Getting a Radio Button State 592 Setting the Radio Button State 594 Programming Selection Lists 594 The Select Object 595 The Option Object 595 Referencing an Option In a Selection List 596 Getting the Currently Selected List Option 596 Getting Multiple Selected Options 597 Setting the Selected List Option 598 Creating a Navigation List 599 Modifying a List On-the-Fly 601 29 Performing Form Validation 605 The Need for Browser-Based Validation 606 Displaying the Form Data for Confirmation 607 Making Form Fields Mandatory 612 First, a Trick: Adding Custom Properties to an Object 613 Checking for Empty Fields 615 Checking for Fields that Contain Only Whitespace Characters 617 Validating the Field Data Type 618 Checking for Alphabetic Data 619 Checking for Integer Data 620 Checking for Signed Integer Data 621 Checking for Floating-Point Data 622 [...]... Getting Started with JavaScript 1 An Overview of JavaScript 11 2 Creating Your First Scripts 17 CHAPTER An Overview of JavaScript In this chapter JavaScript: Controlling the Machine 12 What Is a Programming Language? 12 Is JavaScript Hard to Learn? 14 What Can You Do with JavaScript? What Can’t You Do with JavaScript? Cross-Browser Concerns 16 14 15 1 12 Chapter 1 An Overview of JavaScript JavaScript: Controlling... versions of JavaScript that have appeared over the years The original JavaScript was supported by Netscape 2 and Internet Explorer 3 Here are the initial browser versions that supported subsequent JavaScript releases: JavaScript 1.1 Netscape 3.01 JavaScript 1.2 Internet Explorer 4.01, Netscape 4.05 JavaScript 1.3 Internet Explorer 5.0, Netscape 4.61 JavaScript 1.4 Mozilla 5.0 Alpha Pre-Release M6 JavaScript. .. 838 Using Netscape’s JavaScript Debugger Pausing a Script 839 Stepping Through a Script 844 Monitoring Script Values 845 B JavaScript Reserved Words and Keywords 849 JavaScript Reserved Words JavaScript Keywords 850 850 838 Contents C Working with Regular Expressions 853 Pattern Matching the String Object Way 854 Pattern Matching the Regular Expression Way 854 Building Regular Expressions 854 Special. .. Regular Expressions 855 Summarizing the Regular Expression Symbols 863 Example: Matching an E-mail Address 864 Using Regular Expressions in Your JavaScript Code 865 Checking the Pattern Using the test() Method 866 The search() Method 868 The replace() Method 870 Index 873 xiii xiv Special Edition Using JavaScript About the Author Paul McFedries is the president of Logophilia Limited, a technical writing company... Address 634 30 JavaScript Project: Creating a Shopping Cart 637 Making the Move to E-Commerce 638 Creating the Project Data 638 Designing the Data 638 Creating the Database Using JavaScript 640 An Overview of the Project 644 Customizing This Project for Your Own Use 646 Setting Up Your Store 646 Understanding the Shopping Cart 649 Using the Shopping Cart 650 Creating the Cart On-the-Fly Using JavaScript. .. language is to be understood by whatever machine is processing the language With JavaScript, that machine is the page-reading machine, the Web browser You can make yourself understood by the page-reading machine by using the proper JavaScript words and by combining them using the proper JavaScript syntax For example, JavaScript s syntax rules tell you that you can combine the words window and open()... Using Browser Version Detection Using Object Detection 737 770 735 Creating a Custom Object Front-End 739 Examining the Object 739 Cross-Browser Style References 741 Creating the Custom Objects 742 Using a Custom Object 746 Defining the Custom Object Methods 746 Other Cross-Browser Functions 763 VIII Appendixes A JavaScript Tools for Debugging Scripts 831 Using the Microsoft Script Debugger 832 Pausing... that someone might visit your page using an ancient browser that doesn’t support JavaScript In that case, the browser will likely attempt to process the JavaScript statements that you insert between the and tags To prevent that, enclose your script statements using the HTML comment tags——like this: JavaScript comments, see “Adding Comments to Your Code,” p 29 You learn about the operator later in the book; see Using the Decrement ( ) Operator,” p 78 Handling Browsers with JavaScript Turned Off Although JavaScript- ignorant browsers are a rarity these days, users who have turned off their browser’s JavaScript functionality aren’t so rare Many people disable JavaScript because... illustrate some JavaScript techniques that you’ll use throughout this book The Tag The basic container for a script is, naturally enough, the HTML tag and its associated end tag For a simple script, the tag is embellished with both the language attribute, which is set to the value JavaScript , and the type attribute, which is set to “text /javascript : . 864 xiii Contents Using Regular Expressions in Your JavaScript Code 865 Checking the Pattern Using the test() Method 866 The search() Method 868 The replace() Method 870 Index 873 Special Edition Using JavaScript xiv About. Started with JavaScript 1 An Overview of JavaScript 11 JavaScript: Controlling the Machine 12 What Is a Programming Language? 12 Is JavaScript Hard to Learn? 14 What Can You Do with JavaScript? . Arithmetic Operators 73 Using the Addition (+) Operator 74 Using the Increment (++) Operator 75 Using the Subtraction and Negation (-) Operators 76 Using the Decrement ( ) Operator 78 Using the Multiplication