No Starch Press The Book Of Java Script, A Practical Guide To Interactive Web Pages 2nd (2007)
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 519
Download | ![]() |
Open PDF In Browser | View PDF |
THE BOOK of ™ JAVASCRIPT 2ND EDITION A P R A C T I C A L G U I D E T O 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. Printed on recycled paper in the United States of America 10 09 08 07 06 123456789 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; info@nostarch.com; www.nostarch.com Library of Congress Cataloging-in-Publication Data Thau. The book of JavaScript : a practical guide to interactive Web pages / Thau!. -- 2nd ed. p. cm. Includes index. ISBN-13: 978-1-59327-106-0 ISBN-10: 1-59327-106-9 1. JavaScript (Computer program language) I. Title. QA76.73.J39T37 2006 005.13'3--dc22 2006011786 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it. I dedicate this revised edition of The Book of JavaScript to my wonderful wife Kirsten Menger-Anderson, who never failed to keep a straight face when I said, “It’s almost done.” BRIEF CONTENTS Foreword by Luke Knowland ......................................................................................... xxi Foreword to the First Edition by Nadav Savio ................................................................ xxiii Acknowledgments ....................................................................................................... xxv Introduction .............................................................................................................. xxvii Chapter 1: Welcome to JavaScript! .................................................................................. 1 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 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 viii Brief Contents CONTENTS IN DETAIL FOREWORD by Luke Knowland FOREWORD TO THE FIRST EDITION by Nadav Savio ACKNOWLEDGMENTS INTRODUCTION xxi xxiii xxv xxvii How This Book Is Organized .................................................................................. xxvii Companion Website ...............................................................................................xxx 1 WELCOME TO JAVASCRIPT! 1 Is JavaScript for You?................................................................................................. 1 Is This Book for You? ................................................................................................. 2 The Goals of This Book .............................................................................................. 2 What Can JavaScript Do? .......................................................................................... 3 What Are the Alternatives to JavaScript?...................................................................... 5 CGI Scripting .............................................................................................. 5 VBScript...................................................................................................... 7 Java ........................................................................................................... 7 Flash .......................................................................................................... 7 JavaScript’s Limitations............................................................................................... 7 JavaScript Can’t Talk to Servers ..................................................................... 7 JavaScript Can’t Create Graphics .................................................................. 8 JavaScript Works Differently in Different Browsers ............................................ 8 Getting Started ......................................................................................................... 8 Where JavaScript Goes on Your Web Pages................................................................ 9 Dealing with Older Browsers .................................................................................... 10 Your First JavaScript ................................................................................................ 12 Summary................................................................................................................ 12 Assignment............................................................................................................. 13 2 USING VARIABLES AND BUILT-IN FUNCTIONS TO UPDATE YOUR WEB PAGES AUTOMATICALLY 15 Variables Store Information ...................................................................................... 16 Syntax of Variables .................................................................................... 16 Naming Variables...................................................................................... 17 Arithmetic with Variables ............................................................................ 18 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 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 When and Where to Place Curly Brackets..................................................... 41 OR and AND ......................................................................................................... 42 OR ........................................................................................................... 43 AND ........................................................................................................ 44 Putting It All Together ............................................................................................... 45 A Few More Details About Boolean Expressions.......................................................... 47 How Netscape Provides Browser-Specific Content ....................................................... 48 Summary................................................................................................................ 50 Assignment............................................................................................................. 50 4 W O R K I N G W IT H R O L L O V E R S 51 A Real-World Example of Rollovers ........................................................................... 52 Triggering Events .................................................................................................... 53 Event Types ............................................................................................... 53 Quotes in JavaScript................................................................................... 55 Clicking the Link to Nowhere ....................................................................... 56 More Interesting Actions.............................................................................. 57 Swapping Images ................................................................................................... 58 Working with Multiple Images .................................................................................. 59 x Contents in D e ta i l What’s with All the Dots? ........................................................................................ 60 The document Object.................................................................................. 60 Object Properties ....................................................................................... 61 Finally, Rollovers! ....................................................................................... 62 Image Preloading....................................................................................... 62 How the Tin House Rollovers Work............................................................................ 64 Summary................................................................................................................ 65 Assignment............................................................................................................. 65 5 OPENING AND MANIPULATING WINDOWS 67 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 Line-by-Line Analysis of Figure 6-12 .............................................................. 94 Defining Variables Properly ...................................................................................... 94 Summary................................................................................................................ 96 Assignment............................................................................................................. 97 Contents in D etai l xi 7 P R O V ID I N G A N D R E C E I V I N G I N F O R M A T I O N WITH FORMS 99 Real-World Examples of Forms................................................................................ 100 Form Basics .......................................................................................................... 101 Text Fields ............................................................................................... 102 Buttons, Checkboxes, and Radio Buttons ..................................................... 102 Select Elements ........................................................................................ 104 Textareas ................................................................................................ 106 Final Form Comments ............................................................................... 106 Forms and JavaScript............................................................................................. 107 Naming Form Elements ............................................................................. 107 Naming Radio Buttons .............................................................................. 108 Naming Options ...................................................................................... 108 Reading and Setting Form Elements ......................................................................... 109 Reading Information from Text Fields .......................................................... 109 Setting the Value of a Text Field ................................................................. 110 Textareas ................................................................................................ 111 Checkboxes............................................................................................. 112 Radio Buttons........................................................................................... 114 Pull-Down Menus and Scrollable Lists .......................................................... 115 Handling Events Using Form Elements ...................................................................... 116 Make this a Shortcut .............................................................................................. 117 Using Pull-Down Menus as Navigational Tools .......................................................... 118 One Last Forms Shortcut......................................................................................... 119 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 xii C on t e n t s i n D e t a i l 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 Associative Arrays................................................................................................. 142 Line-by-Line Analysis of Figure 8-18 ............................................................ 144 Summary.............................................................................................................. 144 Assignment........................................................................................................... 145 9 T IM IN G E V E N TS 147 Real-World Examples of Timing Events..................................................................... 147 Setting an Alarm with setTimeout()........................................................................... 148 Canceling an Alarm with clearTimeout()................................................................... 149 Line-by-Line Analysis of Figure 9-3 .............................................................. 150 Repeating Timed Actions........................................................................................ 150 Line-by-Line Analysis of Figure 9-5 .............................................................. 152 Using parseInt() with Form Elements ............................................................ 152 Clearing Out a Time-Out Before You Set a New One ................................... 153 Declaring Variables That Hold Time-Outs Outside Functions .......................... 153 Building a Clock with Timing Loops ......................................................................... 154 Line-by-Line Analysis of Figure 9-7 .............................................................. 155 How the Book of JavaScript Website’s Timer Works .................................................. 155 How Space.com’s Countdown Script Works............................................................. 157 Calculating Times..................................................................................... 160 Global Variables and Constants................................................................. 160 A Timed Slide Show .............................................................................................. 161 Line-by-Line Analysis of Figure 9-11 ............................................................ 162 A Safer Version of rotateImage() ............................................................................. 163 Why Declaring a Variable Outside a Function Is Unsafe ............................... 163 Why You Can’t Put var Inside a Timing Loop ............................................... 163 The Solution ............................................................................................ 164 The Hitch ................................................................................................ 165 The Solution to the Hitch............................................................................ 165 Why image_array Is Declared Outside the rotateImage() Function.................. 166 Summary.............................................................................................................. 167 Assignment........................................................................................................... 167 10 U S IN G FR A M E S A N D I M A G E M A P S 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 Contents i n Detail xiii 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 Line-by-Line Analysis of Figure 11-2 ............................................................ 194 String Handling..................................................................................................... 196 Breaking Strings Apart .............................................................................. 196 Matching String Patterns with Regular Expressions........................................ 203 How Dictionary.com’s Form Validators Work ........................................................... 207 Line-by-Line Analysis of Figure 11-11 .......................................................... 210 Summary.............................................................................................................. 213 Assignment........................................................................................................... 214 12 S A V IN G V I S IT O R I N F O RM A TI O N W I TH C O O K IE S 215 A Real-World Example of Cookies........................................................................... 216 What Are Cookies?............................................................................................... 216 What Cookies Can and Can’t Do ........................................................................... 217 Working with Cookies ........................................................................................... 218 Setting Cookies........................................................................................ 218 Reading Cookies...................................................................................... 218 Resetting Cookies ..................................................................................... 219 Setting More Than One Piece of Information................................................ 220 Setting the Duration of a Cookie ................................................................ 222 Who Can Read the Cookie?...................................................................... 224 The Whole Cookie ................................................................................... 224 Setting Multiple Cookies............................................................................ 225 Cookie Libraries.................................................................................................... 225 A Cookie-Based Shopping Cart .............................................................................. 226 Adding an Item to the Cart ........................................................................ 227 The Checkout Page................................................................................... 229 The readTheCookie() Function.................................................................... 230 The checkOut() Function ........................................................................... 231 Summary.............................................................................................................. 232 Assignment........................................................................................................... 232 xiv Contents in D e ta i l 13 DYNAMIC HTML 233 Real-World Examples of DHTML.............................................................................. 234 CSS Basics ........................................................................................................... 234 TheTag ......................................................................................... 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 14 AJAX BASICS 261 A Real-World Example of Ajax ............................................................................... 262 Introduction to Ajax ............................................................................................... 263 Asynchronicity—The A in Ajax................................................................... 264 XML—The X in Ajax ................................................................................. 265 JavaScript—The J in Ajax .......................................................................... 265 Creating and Sending Requests .............................................................................. 265 Creating a Request Object ........................................................................ 265 Telling the Object Where to Send the Request ............................................. 266 What to Do When the Request Is Answered ................................................ 266 Writing JavaScript That Is Called After the Request Has Been Answered ......... 268 Sending the Request ................................................................................. 268 Putting Everything Together........................................................................ 269 Getting the Results .................................................................................... 270 Demonstrating Asynchronicity ................................................................................. 271 Line-by-Line Analysis of Figure 14-6 ............................................................ 273 C on t e n t s i n D e t a i l xv Ajax and Usability ................................................................................................ 274 The Back Button ....................................................................................... 274 URLs and Bookmarking ............................................................................. 274 Poor Design............................................................................................. 274 To Ajax, or Not to Ajax ......................................................................................... 275 Bad: Just Because You Can ....................................................................... 275 Bad: It’s the Hot New Thing....................................................................... 275 Bad: Replacing Something That Works with Something New and Confusing ........................................................... 275 Good: In-Context Data Manipulation .......................................................... 276 Good: Interactive Widgets ........................................................................ 276 Good: Saving State .................................................................................. 276 Summary.............................................................................................................. 276 Assignment........................................................................................................... 277 15 X M L IN J A V A S C R I P T A N D A J A X 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 Passing Input in a URL............................................................................... 305 Using PHP to Read the Inputs of a GET Request............................................ 306 xvi Contents in D e ta i l Creating a Google Suggest Application with an Ajax GET Request ............................. 308 Contacting Third-Party Webservers with Ajax and PHP ................................. 308 The JavaScript for the Homemade Google Suggest Application ..................... 309 Using PHP to Contact Other Webservers ..................................................... 313 Ajax and the POST Method .................................................................................... 314 An Ajax-Friendly Form .............................................................................. 316 POSTing with Ajax ................................................................................... 316 Sending XML Information from the Browser to a Webserver........................... 318 HEAD Requests: Getting Information About a Server-Side File .................................... 318 Adding Headers to Your Responses............................................................ 319 Headers and XML .................................................................................... 320 The Caching Problem ............................................................................................ 320 File Handling in PHP.............................................................................................. 321 Creating and Adding Contents to a Text File with PHP .................................. 321 Reading Files in PHP................................................................................. 322 When Communication Breaks Down........................................................................ 323 Automatically Updating a Web Page When a Server-Side File Changes ...................... 325 readFileDoFunction()................................................................................. 327 callReadFile() ........................................................................................... 327 callUpdateIfChanged().............................................................................. 328 stopTimer() .............................................................................................. 328 Recap and Breathe................................................................................... 328 The Server-Side PHP Code......................................................................... 328 Summary.............................................................................................................. 329 Assignment........................................................................................................... 330 17 PUTTING IT ALL TOGETHER IN A SHARED TO DO LIST 331 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 Contents in D etai l xvii 18 D E B U G G I N G J A V A S C R IP T A N D A J A X 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 Remember to Use Two Equal Signs in Logical Tests....................................... 366 Use Quotation Marks Correctly .................................................................. 366 Finding Bugs......................................................................................................... 367 Printing Variables with alert() Statements ..................................................... 367 Debugging Beyond Alerts.......................................................................... 369 Using Your Browser’s Bug Detector............................................................. 370 Using JavaScript Debuggers ...................................................................... 370 Debugging Ajax in Firefox 1.5 and 2.0 ...................................................... 374 Other Debugging Resources ...................................................................... 376 Fixing Bugs .......................................................................................................... 376 Back Up Your Program ............................................................................. 377 Fix One Bug at a Time .............................................................................. 377 Avoid Voodoo Coding.............................................................................. 377 Look for Similar Bugs ................................................................................ 378 Clear Your Head...................................................................................... 378 Ask for Help ............................................................................................ 378 Summary.............................................................................................................. 379 A A N S W E R S T O A S S IG N M E N T S Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter xviii 381 2 ............................................................................................................ 381 3 ............................................................................................................ 383 4 ............................................................................................................ 383 5 ............................................................................................................ 384 index.html ............................................................................................... 384 image_page.html ..................................................................................... 384 6 ............................................................................................................ 385 7 ............................................................................................................ 385 8 ............................................................................................................ 387 9 ............................................................................................................ 389 10 .......................................................................................................... 390 index.html ............................................................................................... 390 assignment-nav.html.................................................................................. 390 blank.html ............................................................................................... 391 11 .......................................................................................................... 391 index.html ............................................................................................... 391 assignment-nav.html.................................................................................. 392 blank.html ............................................................................................... 394 12 .......................................................................................................... 394 13 .......................................................................................................... 395 C on t e n t s i n D e t a i l 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 Ruby....................................................................................................... 410 C REFERENCE TO JAVASCRIPT OBJECTS AND FUNCTIONS 411 alert()................................................................................................................... 413 Anchor ................................................................................................................ 413 Applet ................................................................................................................. 413 Area.................................................................................................................... 414 Array................................................................................................................... 414 Button (Including Submit and Reset Buttons) .............................................................. 416 Checkbox............................................................................................................. 417 clearInterval()........................................................................................................ 417 clearTimeout() ....................................................................................................... 417 confirm() .............................................................................................................. 418 Date .................................................................................................................... 418 Document............................................................................................................. 421 elements[] ............................................................................................................ 423 escape()............................................................................................................... 423 eval() ................................................................................................................... 423 Event ................................................................................................................... 423 FileUpload ........................................................................................................... 424 Form.................................................................................................................... 424 Hidden ................................................................................................................ 426 History ................................................................................................................. 426 HTMLElement........................................................................................................ 427 Image .................................................................................................................. 429 C o n te n t s i n D e t a i l xix isNaN() ............................................................................................................... 430 Link ..................................................................................................................... 431 Location ............................................................................................................... 431 Math ................................................................................................................... 432 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 saveXMLFile.php ...................................................................................... 467 INDEX xx Co ntents i n Detail 469 FOREWORD The first JavaScript I remember writing was a routine to change two frames at the same time. I was the production specialist for HotWired, and it was shortly after frames and JavaScript debuted, well before there was documentation for either. Fortunately, it was also well before Internet Explorer 3.0 appeared on the scene, so I only had to make sure my JavaScript worked for Netscape 2.0. Even so, without a reference book to point out where possible pitfalls could be or answer simple questions such as how to set variables that JavaScript would like or how to make different windows talk to each other, it was one hell of a challenge. And it was deeply satisfying when I got it to work correctly. When Dave asked me to do the technical review of the second edition of The Book of JavaScript, I couldn’t have been more pleased or honored. The deep satisfaction I felt when I wrote those first JavaScripts and they worked correctly, and the deeper satisfaction I felt as more and more browsers were released and I figured out how to write cross-browser and cross-platform JavaScript, are the same feelings I got when I read Dave’s explanations and examples. He describes what a piece of code is going to do and how to think about it, then lays out an example of code that makes sense—whether you’re a seasoned programmer or entirely new to JavaScript. On top of all that, he takes a practical approach to programming, he’s able to explain complex problems in a way that doesn’t make them sound daunting, and when you’re done covering each topic, you feel like you’ve earned the knowledge. That’s rare, and it’s really, really refreshing. Since the first edition of this book was published, there have been a few advancements in JavaScript, most notably the advent of Ajax. Ajax is a concept that makes even a few professional programmers’ heads spin, but (not surprisingly) 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 xxii F o r e w or d 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 consider yourself lucky to have Thau as a teacher. You couldn’t do better. Happy JavaScripting! Nadav Savio Principal, Giant Ant Design San Francisco ACKNOWLEDGMENTS This second edition of The Book of JavaScript took me much longer to complete than I could have imagined. I’d like to thank the entire No Starch Press staff for putting up with all the delays and surprise extra bits. I would especially like to thank Christina Samuell for moving the process along, William Pollock, Riley Hoffman, Jerome Colburn, and Stephanie Provines for extensive edits, and Luke Knowland for making sure all the code works and offering many excellent suggestions. I’d also like to thank my neighbor, Laurentino Padilla, for sweeping our sidewalk on Thursdays. Without him, this book would have taken even longer to finish. INTRODUCTION You are about to begin a journey through JavaScript— a programming language that adds interactivity and spark to web pages all over the Internet. This book, written primarily for nonprogrammers, provides scripts you can cut and paste for use on your website, but it also explains how they work, so you’ll soon be writing your own scripts. Each chapter focuses on a few important JavaScript features, shows you how professional websites incorporate those features, and gives you examples of how you might add those features to your own web pages. How This Book Is Organized Before you dive in, here is a quick overview of what you’ll learn as you make your way through The Book of JavaScript. Have fun! Chapter 1: Welcome to JavaScript! This chapter lays out the book’s goals, introduces you to JavaScript and compares it to other tools, describes some of the nifty ways in which JavaScript can enhance your web pages, and walks you through writing your first JavaScript. Chapter 2: Using Variables and Built-in Functions to Update Your Web Pages Automatically Did you know that JavaScript can figure out what day it is and write the date to a web page? This chapter will show you how. Along the way you’ll also learn how JavaScript remembers things using variables and performs actions using functions. Chapter 3: Giving the Browsers What They Want In this chapter you’ll learn how to direct someone to a web page specifically designed for his or her browser. You’ll figure out which browser the visitor is using, then you’ll use if-then statements and their kin to point the visitor in the right direction. Chapter 4: Working with Rollovers This chapter covers everyone’s favorite JavaScript trick—the image swap. You’ll also learn how to trigger JavaScript based on a viewer’s actions. Chapter 5: Opening and Manipulating Windows This chapter explains everything you need to know about opening new browser windows—another favorite JavaScript trick. You’ll also learn how JavaScript writes HTML to the new windows, closes them, and moves them around on the screen. Chapter 6: Writing Your Own JavaScript Functions Functions are the major building blocks of any JavaScript program, so learning to write your own is a critical step toward JavaScript mastery. This chapter gives you the tools you’ll need to write your own functions and put them to work. Chapter 7: Providing and Receiving Information with Forms This chapter shows you how JavaScript works with HTML forms to collect all kinds of information from your users and give them fancy ways to navigate your site. Chapter 8: Keeping Track of Information with Arrays and Loops JavaScript calls lists arrays, and they come in very handy. This chapter describes how JavaScript deals with these lists, whether they include all the images on a web page or all the friends in your address book. Chapter 9: Timing Events This chapter discusses setting events to occur at specific times. For example, you can open a window and then close it in five seconds, or you can write a clock that updates every second. Once you know how to do this, you can create games and other interactive applications based on timed events. xxviii I n t ro d u c t i o n Chapter 10: Using Frames and Image Maps How JavaScript works with HTML frames and image maps is the subject of this chapter. It covers topics including changing two or more frames at once and preventing your web page from getting trapped in someone else’s frame set. Chapter 11: Validating Forms, Massaging Strings, and Working with Server-Side Programs This chapter shows you how to make sure people are filling out your HTML forms completely. Along the way, you’ll learn fancy ways to check user input—for example, you’ll learn how to check the formatting of an email address. Chapter 12: Saving Visitor Information with Cookies Cookies are bits of code that let your web pages save information a visitor has provided even after he or she turns off the computer. This allows your site to greet a guest by name whenever he visits (if he tells you his name, of course!). Chapter 13: Dynamic HTML This chapter introduces Dynamic HTML, a feature of newer browsers that lets you animate entire web pages. Chapter 14: Ajax Basics This chapter begins a trilogy of chapters on Ajax, a programming technique that helps you build websites that act like desktop applications. Here you’ll be introduced to Ajax and most of the JavaScript you’ll need to know to create Ajax applications. Chapter 15: XML in JavaScript and Ajax The X in Ajax stands for XML. This chapter describes how to represent information using the XML data-sharing standard and process XML documents using JavaScript. Chapter 16: Server-Side Ajax You’ll wrap up your introduction to Ajax with instructions for writing programs that run on webservers. This chapter touches on the PHP programming language and shows you how PHP programs store files on webservers and contact other webservers for information. Chapter 17: Putting It All Together in a Shared To Do List In this chapter you’ll apply everything you learned in the first 16 chapters and create a collaborative To Do list application. Not much new material will be introduced, but you’ll see how everything we’ve covered so far fits together. Chapter 18: Debugging JavaScript and Ajax This chapter wraps things up by giving you tips for what to do when the JavaScript you’ve written isn’t working correctly. Appendix A: Answers to Assignments Here you’ll find answers to the assignments that end each chapter. I n t r od u ct i o n xxix Appendix B: Resources This appendix provides information about the many JavaScript and Ajax libraries you can use to further enhance your web pages. Appendix C: Reference to JavaScript Objects and Functions This appendix lists all of the objects and functions that comprise JavaScript. Appendix D: Chapter 15’s Italian Translator and Chapter 17’s To Do List Application The last appendix gives a couple of the book’s longest code examples in their entirety. Companion Website The Book of JavaScript website (http://www.bookofjavascript.com) contains the code examples from each chapter, archived copies of many of the websites mentioned, and lots of script libraries and freeware. You’ll find that each chapter has its own directory, complete with the example scripts and relevant images from that chapter, as well as the answer to that chapter’s assignment. Here’s a rundown of the directories. /Chapter01, /Chapter02, and so on Each chapter has its own directory. For example, the code examples from Chapter 1 are available at http://www.bookofjavascript.com/ Chapter01. /Freeware This directory contains free software you may find useful, including: z XAMPP webserver and PHP packages for Windows and Linux z MAMP webserver and PHP packages for Macintosh z Flock social web browser z Venkman JavaScript debugger for Firefox z Firefox 2.0 browser /Libraries This directory contains free JavaScript libraries you can cut and paste into your website, including: z Prototype JavaScript Framework z Webmonkey Cookie Library z Sarissa XML Toolkit /Websites This directory contains HTML (including JavaScript) and images for many of the websites discussed in the book. xxx I n t r o d u c ti o n WELCOME TO JAVASCRIPT! Welcome to The Book of JavaScript. JavaScript is one of the fastest and easiest ways to make your website truly dynamic— that is, interactive. If you want to spruce up tired-looking pages, you’ve got the right book. This book will give you some ready-made JavaScripts you can implement immediately on your website, but, more importantly, it will take you step by step through sample scripts (both hypothetical and real-world examples) so that you understand how JavaScript works. With this understanding you can modify existing scripts to fit your specific needs as well as write scripts from scratch. Your knowledge of JavaScript will grow as you work through the book; each chapter introduces and explores in depth a new JavaScript topic by highlighting its application in real-life situations. Is JavaScript for You? If you want a quick, easy way to add interactivity to your website, if the thought of using complex programming languages intimidates you, or if you’re interested in programming but simply don’t know where to start, JavaScript is for you. JavaScript, a programming language built into your web browser, is one of the best ways to add interactivity to your website because it’s the only crossbrowser language that works directly with web browsers. Other languages such as Java, Perl, PHP, and C don’t have direct access to the images, forms, and windows that make up a web page. JavaScript is also very easy to learn. You don’t need any special hardware or software, you don’t need access to a webserver, and you don’t need a degree in computer science to get things working. All you need is a web browser and a text editor such as SimpleText or Notepad. Finally, JavaScript is a complete programming language, so if you want to learn more about programming, it provides a great introduction. (If you don’t give a hoot about programming, that’s fine too. There are plenty of places— including this book and its companion website—where you can get prefab scripts to cut and paste right into your pages. But you’ll get much more out of the book by using it as a tool for learning JavaScript programming.) Is This Book for You? This book assumes you don’t have any programming background. Even if you have programmed before, you’ll find enough that’s new in JavaScript to keep you entertained. One of the best things about JavaScript is that you don’t have to be a mega-expert to get it working on your web pages right away. You do need a working knowledge of HTML, however. The Goals of This Book The main goal of this book is to get you to the point of writing your own JavaScripts. An important tool in learning to write scripts is the ability to read other people’s scripts. JavaScript is a sprawling language, and you can learn thousands of little tricks from other scripts. In fact, once you’ve finished this book, you’ll find that viewing the source code of web pages that use JavaScript is the best way to increase your knowledge. Each of the following chapters includes JavaScript techniques used in building professional sites. Along the way, I’ll point out sites that use the technique described, and by viewing the source code of such sites you’ll soon see there are many ways to script. Sometimes going through a site’s code reveals interesting aspects of JavaScript that I don’t cover in this book. Beyond learning how to write your own JavaScript and read other people’s scripts, I also want you to learn where to look for additional information on JavaScript. As I’ve noted, the best place to learn new techniques is to view the source code of web pages you find interesting. However, several websites also offer free JavaScripts. I’ll be introducing some of these as we go along, but here are a few good examples to get you started: 2 Chapter 1 z http://www.webmonkey.com/reference/javascript_code_library z http://javascript.internet.com z http://www.scriptsearch.com/JavaScript/Scripts z http://www.javascriptsearch.com Another good place to get information is a JavaScript reference book. The Book of JavaScript is primarily a tutorial for learning basic JavaScript and making your website interactive. It’s not a complete guide to the language, which includes too many details for even a lengthy introduction to cover. If you’re planning to become a true JavaScript master, I suggest picking up JavaScript: The Definitive Guide by David Flanagan (O’Reilly, 2006) after making your way through this book. The last 500 or so pages of Flanagan’s book list every JavaScript command and the browsers in which it works. What Can JavaScript Do? JavaScript can add interactivity to your web pages in a number of ways. This book offers many examples of JavaScript’s broad capabilities. The following are just two examples that illustrate what you can do with JavaScript. The first example (Figure 1-1) is a flashing grid of colored squares (to get the full effect, browse to http://www.bookofjavascript.com/Chapter01/ Fig01-01.html), created by a fellow named Taylor way back in 1996. Flashy, isn’t it? In this example, a JavaScript function changes the color of a randomly chosen square in the grid every second or so. Figure 1-1: A demonstration of JavaScript’s artful abilities W e l co me t o Jav aS c r i p t ! 3 Mousing over one of the five icons below the squares (number, plus sign, square, letter, and horizontal line) tells the page to use a new set of images on the grid. For example, mousing over the number icon tells the JavaScript to start replacing the squares with 1s and 0s. This page illustrates four important JavaScript features you’ll learn about throughout the book: z How to change images on a web page z How to affect web pages over time z How to add randomness to web pages z How to dynamically change what’s happening on a web page based on an action taken by someone viewing the page Although Taylor’s demo is beautiful, it’s not the most practical application of JavaScript. Figure 1-2 (available at http://www.bookofjavascript.com/ Chapter01/Fig01-02.html) shows you a much more practical use of JavaScript that calculates the weight of a fish based on its length. Enter the length and type of fish, and the JavaScript calculates the fish’s weight. This fishy code demonstrates JavaScript’s ability to read what a visitor has entered into a form, perform a mathematical calculation based on the input, and provide feedback by displaying the results in another part of the form. You may not find calculating a fish’s weight a particularly useful application of JavaScript either, but you can use the same skills to calculate a monthly payment on a loan (Chapter 7), score a quiz (Chapter 10), or verify that a visitor has provided a valid email address (Chapter 11). Figure 1-2: How much does my fish weigh? 4 Chapter 1 These are just two examples of the many features JavaScript can add to your websites. Each chapter will cover at least one new application. If you want a preview of what you’ll learn, read the first page or so of each chapter. What Are the Alternatives to JavaScript? Several other programming languages can add interactivity to web pages, but they all differ from JavaScript in important ways. The four main alternatives are CGI scripting, Java, VBScript, and Flash. CGI Scripting Before JavaScript, using CGI scripts was the only way to make web pages do more than hyperlink to other web pages containing fixed text. CGI stands for Common Gateway Interface. It’s a protocol that allows a web browser running on your computer to communicate with programs running on webservers. It is most often used with HTML forms—pages where the user enters information and submits it for processing. For example, the user might see a web page containing places for entering the length and selecting the type of a fish, as well as a Compute button. When the user keys in the length, selects the type, and clicks the button, the information is sent to a CGI script on the server. The CGI script (which is probably written in a programming language like Perl, PHP, or C) receives the information, calculates the weight of the fish, and sends the answer, coded as an HTML page, back to the browser. CGI scripts are very powerful, but because they reside on webservers, they have some drawbacks. The Need for Back-and-Forth Communication First, the connection between your web browser and the webserver limits the speed of your web page’s interactivity. This may not sound like a big problem, but imagine the following scenario: You’re filling out an order form with a dozen entry fields including name, address, and phone number (see Figure 1-3), but you forget to fill out the phone number and address fields. When you click the Submit button to send the information across the Internet to the webserver, the CGI script sees that you didn’t fill out the form completely and sends a message back across the Internet requesting that you finish the job. This cycle could take quite a while over a slow connection. If you fill out the form incorrectly again, you have to wait through another cycle. People find this process tiresome, especially if they’re customers who want their orders processed quickly. With JavaScript, though, the programs you write run in the browser itself. This means that the browser can make sure you’ve filled out the form correctly before sending the form’s contents to the webserver. JavaScript thus reduces the time your information spends traveling between the browser and the server. W e l co me t o Jav aS c r i p t ! 5 Figure 1-3: A simple order form Server Overload by Concurrent Access Another drawback to CGI scripts is that a webserver running a CGI program can get bogged down if too many people call the script simultaneously (for example, if too many fishermen decided to run the weight calculator and click the Compute button at the same time). Serving up HTML pages is pretty easy for a webserver. However, some CGI scripts take a long time to run on a machine, and each time someone calls the script, the server has to start up another copy of it. As more and more people try to run the script, the server slows down progressively. If a thousand people are trying to run the script at once, the server might take so long to respond that either the user or the browser gives up, thinking the server is dead. This problem doesn’t exist in JavaScript because its scripts run on each visitor’s web browser—not on the webserver. Security Restrictions A third problem with CGI scripts is that not everyone has access to the parts of a webserver that can run CGI scripts. Since a CGI script can conceivably crash a webserver or exploit security flaws, system administrators generally guard these areas, only allowing fellow administrators access. If you have Internet access through an Internet service provider (ISP), you may not be allowed to write CGI scripts. If you are designing web pages for a company, you may not be given access to the CGI-enabled areas of the webserver. 6 Chapter 1 JavaScript, on the other hand, goes right into the HTML of a web page. If you can write a web page, you can put JavaScript in the page without permission from recalcitrant administrators. VBScript The language most similar to JavaScript is Microsoft’s proprietary language, VBScript (VB stands for Visual Basic). Like JavaScript, VBScript runs on your web browser and adds interactivity to web pages. However, VBScript works only on computers running Internet Explorer (IE) on Microsoft Windows, so unless you want to restrict your readership to people who use IE on Windows, you should go with JavaScript. Java Although JavaScript and Java have similar names, they aren’t the same. Netscape, now a part of AOL, initially created JavaScript to provide interactivity for web pages, whereas Sun Microsystems wrote Java as a general programming language that works on all kinds of operating systems. Flash Flash is a tool from Macromedia developed to add animation and interactivity to websites. Almost all modern browsers can view Flash animations or can easily download the Flash plug-in. Flash animations look great, and a basic Flash animation requires no programming skills at all. To create Flash animations, however, you must purchase a Flash product from Macromedia. While some people consider Flash and JavaScript to be competitors, that’s not the case. In fact, you can call JavaScript programs from Flash, and you can manipulate Flash animations using JavaScript. Web page designers will often blend the two, using Flash for animations and JavaScript for interactivity that does not involve animations. Flash animations can also be made more interactive using a language called ActionScript, which is almost exactly like JavaScript. JavaScript’s Limitations Yes, JavaScript does have limitations, but these limitations are natural and unavoidable by-products of its main purpose: to add interactivity to your web pages. JavaScript Can’t Talk to Servers One of JavaScript’s drawbacks is also its main strength: It works entirely within the web browser. As we’ve seen, this cuts down on the amount of time your browser spends communicating with a webserver. On the other hand, this also means that JavaScript can’t communicate with other machines and therefore can’t handle some server tasks you may need to do. W e l co me t o Jav aS c r i p t ! 7 For example, JavaScript can’t aggregate information collected from your users. If you want to write a survey that asks your visitors a couple of questions, stores their answers in a database, and sends a thank-you email when they finish, you’ll have to use a program that runs on your webserver. As we’ll see in Chapter 7, JavaScript can make the survey run more smoothly, but once a visitor has finished filling out the questions, JavaScript can’t store the information on the server, because it can’t contact the server. In order to store the survey information, you need to use a program that runs on a webserver. Sending email with JavaScript is also impossible, because to send email JavaScript would have to contact a mail server. Again, you need a server-side program for this job. Although JavaScript can’t directly control programs that run on webservers, it can ask webservers to run programs, and it can send information to those programs. We’ll see examples of that in Chapters 7 and 14, and we’ll get a taste for writing server-side programs in Chapters 15 and 16. JavaScript Can’t Create Graphics Another of JavaScript’s limitations is that it can’t create its own graphics. Whereas more complicated languages can draw pictures, JavaScript can only manipulate existing pictures (that is, GIF or JPEG files). Luckily, because JavaScript can manipulate created images in so many ways, you shouldn’t find this too limiting. JavaScript Works Differently in Different Browsers Perhaps the most annoying problem with JavaScript is that it works somewhat differently in different browsers. JavaScript was introduced in 1996 by Netscape in version 2 of Netscape Navigator. Since then, JavaScript has changed, and every browser implements a slightly different version of it—often adding browser-specific features. Luckily, starting in the late 1990s, the European Computer Manufacturers Association (ECMA) began publishing standards for JavaScript, which they call ECMAScript. About 99 percent of all browsers being used today comply with at least version 3 of the ECMA standard. These include Internet Explorer version 5.5 and later, Netscape version 6 and later, Mozilla, Firefox, all versions of Safari, and Opera version 5 and later. Because almost all browsers currently in use adhere to version 3 of the ECMA standard, I’ll be using that as the standard version of JavaScript in the book. Where incompatibilities between browsers arise, I’ll point them out. Getting Started We’re about ready to begin. To write JavaScripts, you need a web browser and a text editor. Any text editor will do: Notepad or WordPad in Windows and SimpleText on a Macintosh are the simplest choices. Microsoft Word or Corel’s WordPerfect will work as well. You can also use a text editor such as BBEdit or HomeSite, which are designed to work with HTML and JavaScript. Some tools for building websites will actually write JavaScript for you— for example, Adobe’s Dreamweaver and GoLive. These tools work fine when 8 Chapter 1 you want to write JavaScripts for common features such as image rollovers and you know you’ll never want to change them. Unfortunately, the JavaScript often ends up much longer than necessary, and you may find it difficult to understand and change to suit your needs. Unless you want a JavaScript that works exactly like one provided by the package you’ve purchased, you’re often best off writing scripts by hand. Of course, you can also use one of these tools to figure out how you want your page to behave and then go back and rewrite the script to suit your specific needs. NOTE Always save documents as text only, and end their names with .html or .htm. If you’re using Microsoft Word or WordPerfect and you don’t save your documents as text-only HTML or HTM files, both programs will save your documents in formats web browsers can’t read. If you try to open a web page you’ve written and the browser shows a lot of weird characters you didn’t put in your document, go back and make sure you’ve saved it as text only. Where JavaScript Goes on Your Web Pages Now let’s get down to some JavaScript basics. Figure 1-4 shows you the thinnest possible skeleton of an HTML page with JavaScript.JavaScript Skeleton X Figure 1-4: An HTML page with JavaScript In Figure 1-4, you can see the JavaScript between the tags in X and Y. Note that you can also start JavaScript with this tags. Furthermore, you can’t include any HTML between . Between those tags, your browser assumes that everything it sees is JavaScript. If it sees HTML in there, or anything else it can’t interpret as JavaScript, it gets confused and gives you an error message. These JavaScript tags can go in either the head (between and ) or the body (between and ) of your HTML page. It doesn’t matter too much where you put them, although you’re generally best off putting as much JavaScript in the head as possible. That way you don’t have to look for it all over your web pages. One final thing worth mentioning here is that the lines that start with two slashes are JavaScript comments. The browser ignores any text that appears after two slashes. Documenting your work with comments is extremely important, because programming languages aren’t easily understood. The script you’re writing may make perfect sense while you’re writing it, but a few days later, when you want to make a little modification, you might spend hours just figuring out what you wrote the first time. If you comment your code, you’ll have a better chance to save yourself the hassle of remembering what you were thinking when you wrote that bizarre code at 2 AM in the midst of what seemed like an amazingly lucid caffeine haze. Dealing with Older Browsers There’s a slight problem with the JavaScript skeleton in Figure 1-4 (besides the fact that it doesn’t really have any JavaScript in it): Netscape didn’t introduce the Figure 1-6: Hiding JavaScript from browsers that don’t understand it The important symbols are the comments in Y. These weird lines work because in HTML, the are tags that mark the beginning and end of an entire block of comments. Older browsers that don’t recognize the , and people with older browsers will thank you. Wel c o me t o J a v a S cr i pt ! 11 Your First JavaScript It’s time to run your first JavaScript program. I’ll explain the code in Figure 1-7 in the next chapter, so for now, just type the code into your text editor, save it as my_first_program.html, and then run it in your browser. If you don’t want to type it all in, run the example at http://www.bookofjavascript.com/ Chapter01/Fig01-07.html.JavaScript Skeleton Figure 1-7: Your first JavaScript program When a browser reads this file, the JavaScript in X instructs the browser to put up a little window with the words Hello, world! in it. Figure 1-8 shows you what this looks like in a web browser. Traditionally, this is the first script you write in any programming language. It gets you warmed up for the fun to come. Figure 1-8: Window launched by the “Hello, world!” script Summary Congratulations—you’re now on your way to becoming a bona fide JavaScripter! This chapter has given you all the basic tools you need and has shown you how to get a very basic JavaScript program running. If you followed everything here, you now know: 12 Chapter 1 z Some of the great things JavaScript can do z How JavaScript compares to CGI scripting, VBScript, Java, and Flash z JavaScript’s main limitations z Where JavaScript goes on the page z How to write JavaScript older browsers won’t misunderstand Assignment Try typing Figure 1-7 into a text editor and running it in a web browser. You’ll find the next chapter’s assignments hard to do if you can’t get Figure 1-7 to work. If you’re sure you’ve recreated Figure 1-7 exactly and it’s not working, make sure you’re saving the file as text only. You may also find it helpful to peruse Chapter 14, which discusses ways to fix broken code. Although you may not understand everything in that chapter, you may find some helpful tips. If it’s still not working, try running the version of Figure 1-7 at http:// www.bookofjavascript.com/Chapter01/Fig01-07.html. If that doesn’t work, you may be using a browser that doesn’t support JavaScript, or your browser may be set to reject JavaScript. If you’re sure you’re using a browser that supports JavaScript (Netscape 2.0 and later versions, and Internet Explorer 3.0 and later), check your browser’s options and make sure it’s set to run JavaScript. Once you’re comfortable with the concepts covered in this chapter, you’ll be ready to write some code! Wel c o me t o J a v a S cr i pt ! 13 USING VARIABLES AND BUILT-IN FUNCTIONS TO UPDATE YOUR WEB PAGES AUTOMATICALLY With JavaScript you can update the content of your pages automatically—every day, every hour, or every second. In this chapter, I’ll focus on a simple script that automatically changes the date on your web page. Along the way you’ll learn: z How JavaScript uses variables to remember simple items such as names and numbers z How JavaScript keeps track of more complicated items such as dates z How to use JavaScript functions to write information to your web page Before getting into the nuts and bolts of functions and variables, let’s take a look at a couple of examples of web pages that automatically update themselves, starting with the European Space Agency (http://www.esa.int). As you can see in Figure 2-1, the ESA’s home page shows you the current date. Rather than change the home page every day, the ESA uses JavaScript to change the date automatically. Figure 2-1: Using JavaScript to display the current date An even more frequently updated page is the home page of the Book of JavaScript website (http://www.bookofjavascript.com), which updates the time as well as the date (see Figure 2-2). You don’t have to sit in front of your computer, updating the dates and times on your websites. JavaScript can set you free! The ability to write HTML to web pages dynamically is one of JavaScript’s most powerful features. Figure 2-2: Dynamically updating the date and time To understand how to update the date and time on the page, you’ll first have to learn about variables, strings, and functions. Your homework assignment at the end of this chapter will be to figure out how to add seconds to the time. Variables Store Information Think back to those glorious days of algebra class when you learned about variables and equations. For example, if x = 2, y = 3, and z = x + y, then z = 5. In algebra, variables like x, y, and z store or hold the place of numbers. In JavaScript and other programming languages, variables also store other kinds of information. Syntax of Variables The syntax of variables (the set of rules for defining and using variables) is slightly different in JavaScript from what it was in your algebra class. Figure 2-3 illustrates the syntax of variables in JavaScript with a silly script that figures out how many seconds there are in a day. NOTE 16 Chapter 2 Figure 2-3 does not write the results of the JavaScript to the web page—I’ll explain how to do that in Figure 2-4.Seconds in a Day Know how many seconds are in a day?
I do!
Figure 2-3: Defining and using variables There’s a lot going on here, so let’s take it line by line. Line X is a statement (a statement in JavaScript is like a sentence in English), and it says to JavaScript, “Create a variable called seconds_per_minute and set its value to 60.” Notice that X ends with a semicolon. Semicolons in JavaScript are like periods in English: They mark the end of a statement (for example, one that defines a variable, as above). As you see more and more statements, you’ll get the hang of where to place semicolons. The first word, var, introduces a variable for the first time—you don’t need to use it after the first instance, no matter how many times you employ the variable in the script. NOTE Many people don’t use var in their code. Although most browsers let you get away without it, it’s always a good idea to put var in front of a variable the first time you use it. (You’ll see why when I talk about writing your own functions in Chapter 6.) Naming Variables Notice that the variable name in X is pretty long—unlike algebraic variables, it’s not just a single letter like x, y, or z. When using variables in JavaScript (or any programming language), you should give them names that indicate what piece of information they hold. The variable in X stores the number of seconds in a minute, so I’ve called it seconds_per_minute. If you name your variables descriptively, your code will be easier to understand while you’re writing it, and much easier to understand when you return to it later for revision or enhancement. Also, no matter which programming U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 17 language you use, you’ll spend about 50 percent of your coding time finding and getting rid of your mistakes. This is called debugging—and it’s a lot easier to debug code when the variables have descriptive names. You’ll learn more about debugging in Chapter 14. There are four rules for naming variables in JavaScript: 1. The initial character must be a letter, an underscore, or a dollar sign, but subsequent characters may be numbers as well. 2. No spaces are allowed. 3. Variables are case sensitive, so my_cat is different from My_Cat, which in turn is different from mY_cAt. As far as the computer is concerned, each of these would represent a different variable—even if that’s not what the programmer intended. (You’ll see an example of this in the section “alert()” on page 22.) To avoid any potential problems with capitalization, I use lowercase for all my variables, with underscores (_) where there would be spaces in ordinary English. 4. You can’t use reserved words. Reserved words are terms used by the JavaScript language itself. For instance, you’ve seen that the first time you use a variable, you should precede it with the word var. Because JavaScript uses the word var to introduce variables, you can’t use var as a variable name. Different browsers have different reserved words, so the best thing to do is avoid naming variables with words that seem like terms JavaScript might use. Most reserved words are fairly short, so using longer, descriptive variable names keeps you fairly safe. I often call my variables things like the_cat, or the_date because there are no reserved words that start with the word the. If you have a JavaScript that you’re certain is correct, but it isn’t working for some reason, it might be because you’ve used a reserved word. Arithmetic with Variables Line Y in Figure 2-3 introduces a new variable called seconds_per_day and sets it equal to the product of the other three variables using an asterisk (*), which means multiplication. A plus sign (+) for addition, a minus sign (-) for subtraction, and a slash (/) for division represent the other major arithmetic functions. When the browser finishes its calculations in our example, it reaches the end of the JavaScript in the head (Z) and goes down to the body of the HTML. There it sees two lines of HTML announcing that the page knows how many seconds there are in a day.Know how many seconds are in a day?
I do!
So now you have a page that knows how many seconds there are in a day. Big deal, right? Wouldn’t it be better if you could tell your visitors what the answer is? Well, you can, and it’s not very hard. 18 Chapter 2 Write Here Right Now: Displaying Results JavaScript uses the write() function to write text to a web page. Figure 2-4 shows how to use write() to let your visitors know how many seconds there are in a day. (The new code is in bold.) Figure 2-5 shows the page this code displays.Seconds in a Day My calculations show that . . .
Figure 2-4: Using write() to write to a web page Figure 2-5: JavaScript’s calculations U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 19 Line-by-Line Analysis of Figure 2-4 Line X in Figure 2-4 writes the words there are to the web page (only the words between the quotes appear on the page). Don’t worry about all the periods and what window and document really mean right now (I’ll cover these topics in depth in Chapter 4, when we talk about image swaps). For now, just remember that if you want to write something to a web page, use window.document.write("whatever");, placing the text you want written to the page between the quotes. If you don’t use quotes around your text, as in window.document.write(seconds_per_day); then JavaScript interprets the text between the parentheses as a variable and writes whatever is stored in the variable (in this case, seconds_per_day) to the web page (see Figure 2-6). If you accidentally ask JavaScript to write out a variable you haven’t defined, you’ll get a JavaScript error. Be careful not to put quotes around variable names if you want JavaScript to know you’re talking about a variable. If you add quotes around the seconds_per_day variable, like this: window.document.write("seconds_per_day"); then JavaScript will write seconds_per_day to the web page. The way JavaScript knows the difference between variables and regular text is that regular text has quotes around it and a variable doesn’t. Strings Any series of characters between quotes is called a string. (You’ll be seeing lots of strings throughout this book.) Strings are a basic type of information, like numbers—and like numbers, you can assign them to variables. To assign a string to a variable, you’d write something like this: var my_name = "thau!"; The word thau! is the string assigned to the variable my_name. You can stick strings together with a plus sign (+), as shown in the bolded section of Figure 2-6. This code demonstrates how to write output to your page using strings.Seconds in a Day My calculations show that . . .
Figure 2-6: Putting strings together Line-by-Line Analysis of Figure 2-6 Line X in Figure 2-6, var first_part = "there are "; assigns the string "there are" to the variable first_part. Line Y, var last_part = " seconds in a day."; sets the variable last_part to the string "seconds in a day." Line Z glues together the values stored in first_part, seconds_per_day, and last_part. The end result is that the variable whole_thing includes the whole string you want to print to the page, there are 86400 seconds in a day. The window.document.write() line then writes whole_thing to the web page. NOTE The methods shown in Figures 2-4 and 2-6 are equally acceptable ways of writing there are 86400 seconds in a day. However, there are times when storing strings in variables and then assembling them with the plus sign (+) is clearly the best way to go. We’ll see a case of this when we finally get to putting the date on a page. More About Functions Whereas variables store information, functions process that information. All functions take the form functionName(). Sometimes there’s something in the parentheses and sometimes there isn’t. You’ve already seen one of JavaScript’s many built-in functions, window.document.write(), which U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 21 writes whatever lies between the parentheses to the web page. Before diving into the date functions that you’ll need to write the date to your web page, I’ll talk about two interesting functions, just so you get the hang of how functions work. alert() One handy function is alert(), which puts a string into a little announcement box (also called an alert box). Figure 2-7 demonstrates how to call an alert(), and Figure 2-8 shows what the alert box looks like.An Alert Box YTo code, perchance to function
Figure 2-7: Creating an alert box The first thing visitors see when they come to the page Figure 2-7 creates is an alert box announcing that I wrote the page (Figure 2-8). The alert box appears because of X, which tells JavaScript to execute its alert() function. While the alert box is on the screen, the browser stops doing any work. Clicking OK in the alert box makes it go away and allows the browser to finish drawing the web page. In this case, that means writing Figure 2-8: The alert box the words To code, perchance to function to the page (Y). The alert() function is useful for troubleshooting when your JavaScript isn’t working correctly. Let’s say you’ve typed in Figure 2-6, but when you run the code, you see that you must have made a typo—it says there are 0 seconds in a day instead of 86400. You can use alert() to find out how the different variables are set before multiplication occurs. The script in Figure 2-9 contains an error that causes the script to say there are “undefined” seconds in a year; and to track down the error, I’ve added alert() function statements that tell you why this problem is occurring. 22 Chapter 2Seconds in a Day My calculations show that . . .
Figure 2-9: Using alert() to find out what’s wrong Line-by-Line Analysis of Figure 2-9 The problem with this script is in X. Notice the accidental capitalization of the first letter in Hours_per_day. This is what causes the script to misbehave. Line \ multiplies the other numbers by the variable hours_per_day, but hours_per_day was not set—remember, JavaScript considers it a different variable from Hours_per_day—so JavaScript thinks its value is either 0 or undefined, depending on your browser. Multiplying anything by 0 results in 0, so the script calculates that there are 0 seconds in a day. The same holds true for browsers that think hours_per_day is undefined. Multiplying anything U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 23 by something undefined results in the answer being undefined, so the browser will report that there are undefined seconds in a day. This script is short, making it easy to see the mistake. However, in longer scripts it’s sometimes hard to figure out what’s wrong. I’ve added Y, Z, and [ in this example to help diagnose the problem. Each of these statements puts a variable into an alert box. The alert in Y will say seconds_per_minute is: 60. The alert in [ will say hours_per_day is: 0, or, depending on your browser, the alert won’t appear at all. Either way, you’ll know there’s a problem with the hours_per_day variable. If you can’t figure out the mistake by reading the script, you’ll find this type of information very valuable. Alerts are very useful debugging tools. prompt() Another helpful built-in function is prompt(), which asks your visitor for some information and then sets a variable equal to whatever your visitor types. Figure 2-10 shows how you might use prompt() to write a form letter.A Form Letter YDear ,
Thank you for coming to my web page. Figure 2-10: Using prompt() to write a form letter Notice that prompt() in X has two strings inside the parentheses: "What's your name?" and "put your name here". If you run the code in Figure 2-10, you’ll see a prompt box that resembles Figure 2-11. (I’ve used the Opera browser in 24 Chapter 2 this illustration; prompt boxes will look somewhat different in IE and other browsers.) If you type Rumpelstiltskin and click OK, the page responds with Dear Rumpelstiltskin, Thank you for coming to my web page. Figure 2-11: Starting a form letter with a prompt box The text above the box where your visitors will type their name ("What's your name?") is the first string in the prompt function; the text inside the box ("put your name here") is the second string. If you don’t want anything inside the box, put two quotes ("") right next to each other in place of the second string to keep that space blank: var the_name = prompt("What's your name?", ""); If you look at the JavaScript in the body (starting in Y), you’ll see how to use the variable the_name. First write the beginning of the heading to the page using normal HTML. Then launch into JavaScript and use document.write(the_name) to write whatever name the visitor typed into the prompt box for your page. If your visitor typed yertle the turtle into that box, yertle the turtle gets written to the page. Once the item in the_name is written, you close the JavaScript tag, write a comma and the rest of the heading using regular old HTML, and then continue with the form letter. Nifty, eh? The prompt() function is handy because it enables your visitor to supply the variable information. In this case, after the user types a name into the prompt box in Figure 2-10 (thereby setting the variable the_name), your script can use the supplied information by calling that variable. Parameters The words inside the parentheses of functions are called parameters. The document.write() function requires one parameter: a string to write to your web page. The prompt() function takes two parameters: a string to write above the box and a string to write inside the box. Parameters are the only aspect of a function you can control; they are your means of providing the function with the information it needs to do its job. With a prompt() function, for example, you can’t change the color of the box, how many buttons it has, or anything else; in using a predefined prompt box, you’ve decided that you don’t need to customize the box’s appearance. You can only change the parameters it specifically provides— U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 25 namely, the text and heading of the prompt you want to display. You’ll learn more about controlling what functions do when you write your own functions in Chapter 6. Writing the Date to Your Web Page Now that you know about variables and functions, you can print the date to your web page. To do so, you must first ask JavaScript to check the local time on your visitor’s computer clock: var now = new Date(); The first part of this line, var now =, should look familiar. It sets the variable now to some value. The second part, new Date(), is new; it creates an object. Objects store data that require multiple pieces of information, such as a particular moment in time. For example, in JavaScript you need an object to describe 2:30 PM on Saturday, January 7, 2006, in San Francisco. That’s because it requires many different bits of information: the time, day, month, date, and year, as well as some representation (in relation to Greenwich Mean Time) of the user’s local time. As you can imagine, working with an object is a bit more complicated than working with just a number or a string. Because dates are so rich in information, JavaScript has a built-in Date object to contain those details. When you want the user’s current date and time, you use new Date() to tell JavaScript to create a Date object with all the correct information. NOTE You must capitalize the letter D in Date to tell JavaScript you want to use the built-in Date object. If you don’t capitalize it, JavaScript won’t know what kind of object you’re trying to create, and you’ll get an error message. Built-in Date Functions Now that JavaScript has created your Date object, let’s extract information from it using JavaScript’s built-in date functions. To extract the current year, use the Date object’s getYear() function: var now = new Date(); var the_year = now.getYear(); Date and Time Methods In the code above, the variable now is a Date object, and the function getYear() is a method of the Date object. Methods are simply functions that are built in to objects. For example, the getYear() function is built in to the Date object and gets the object’s year. Because the function is part of the Date object, it is called a method. To use the getYear() method to get the year of the date stored in the variable now, you would write: now.getYear() 26 Chapter 2 Table 2-1 lists commonly used date methods. (You can find a complete list of date methods in Appendix C.) Table 2-1: Commonly Used Date and Time Methods NOTE Name Description getDate() The day of the month as an integer from 1 to 31 getDay() The day of the week as an integer where 0 is Sunday and 1 is Monday getHours() The hour as an integer between 0 and 23 getMinutes() The minutes as an integer between 0 and 59 getMonth() The month as an integer between 0 and 11 where 0 is January and 11 is December getSeconds() The seconds as an integer between 0 and 59 getTime() The current time in milliseconds where 0 is January 1, 1970, 00:00:00 getYear() The year, but this format differs from browser to browser Notice that getMonth() returns a number between 0 and 11; if you want to show the month to your site’s visitors, to be user-friendly you should add 1 to the month after using getMonth(), as shown in Y in Figure 2-12. Internet Explorer and various versions of Netscape deal with years in different and strange ways: z Some versions of Netscape, such as Netscape 4.0 for the Mac, always return the current year minus 1900. So if it’s the year 2010, getYear() returns 110. z Other versions of Netscape return the full four-digit year except when the year is in the twentieth century, in which case they return just the last two digits. z Netscape 2.0 can’t deal with dates before 1970 at all. Any date before January 1, 1970 is stored as December 31, 1969. z In Internet Explorer, getYear() returns the full four-digit year if the year is after 1999 or before 1900. If the year is between 1900 and 1999, it returns the last two digits. You’d figure a language created in 1995 wouldn’t have the Y2K problem, but the ways of software developers are strange. Later in this chapter I’ll show you how to fix this bug. Code for Writing the Date and Time Now let’s put this all together. To get the day, month, and year, we use the getDate(), getMonth(), and getYear() methods. To get the hour and the minutes, we use getHours() and getMinutes(). Figure 2-12 shows you the complete code for writing the date and time (without seconds) to a web page, as seen on the Book of JavaScript home page. U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 27The Book of JavaScript 28 Chapter 2 _Welcome to the Book of JavaScript Home Page!
Figure 2-12: Writing the current date and time to a web page Line-by-Line Analysis of Figure 2-12 Here are a few interesting things in this example. Getting the Date and Time The lines from X up until Y get the current date and time from the visitor’s computer clock and then use the appropriate date methods to extract the day, month, year, hours and minutes. Although I’m using a variable name date in X to store the date, I could have used any variable name there: the_date, this_moment, the_present, or any valid variable name. Don’t be fooled into thinking that a variable needs to have the same name as the corresponding JavaScript object; in this case, date just seems like a good name. Making Minor Adjustments Before building the strings we will write to the website, we need to make some little adjustments to the date information just collected. Here’s how it works: z Line Y adds 1 to the month because getMonth() thinks January is month 0. z Line Z fixes the Y2K problem discussed earlier in the chapter, in which the getYear() method returns the wrong thing on some older browsers. If you feed fixY2K() the year returned by date.getYear(), it will return the correct year. The fixY2K() function is not a built-in JavaScript function. I had to write it myself. Don’t worry about how the function works right now. z Line [ fixes a minor formatting issue, using another function that’s not built-in. If the script is called at 6 past the hour, date.getMinutes() returns 6. If you don’t do something special with that 6, your time will look like 11:6 instead of 11:06. So fixTime() sticks a zero in front of a number if that number is less than 10. You can use fixTime() to fix the seconds too, for your homework assignment. Getting the String Right Now that we’ve made a few minor adjustments, it’s time to build the strings. Line \ builds the string for the date. Here’s the wrong way to do it: var date_string = "month / day / year"; U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 29 If you wrote your code this way, you’d get a line that says Today is month / day / year. Why? Remember that JavaScript doesn’t look up variables if they’re inside quotes. So place the variables outside the quote marks and glue everything together using plus signs (+): var date_string = month + "/" + day + "/" + year; This may look a little funny at first, but it’s done so frequently that you’ll soon grow used to it. Line ] creates the string to represent the time. It is very similar to \. Line ^ puts \ and ] together to create the string that will be written to the website. Lines \ through ^ could all have been written as one long line: var date_time_string = "Today is " + month + "/" + day + "/" + year + ". The time is now " + hour + ":" + minutes + "."; However, using three lines makes the code easier for people to read and understand. It’s always best to write your code as if other people are going to read it. What Are Those Other Functions? The JavaScript between ^ and _ defines the fixY2K() and fixTime() functions. Again, don’t worry about these lines for now. We’ll cover how to write your own functions in glorious detail in Chapter 6. JavaScript and HTML Make sure to place your JavaScript and HTML in the proper order. In Figure 2-12, the welcoming HTML in _ precedes the JavaScript that actually writes the date and time in `, since the browser first writes that text and then executes the JavaScript. With JavaScript, as with HTML, browsers read from the top of the page down. I’ve put document.write() in the body so that the actual date information will come after the welcome text. I’ve put the rest of the JavaScript at the head of the page to keep the body HTML cleaner. Why document.write()? Notice that the code in Figure 2-11 uses document.write() instead of window.document.write(). In general, it’s fine to drop the word window and the first dot before the word document. In future chapters I’ll tell you when the word window must be added. How the European Space Agency Writes the Date to Its Page The JavaScript used by the European Space Agency is very much like the code I used for the Book of JavaScript web page. One big difference between the two is that the ESA prints out the month using abbreviations like Jan and Feb for January and February. They do this using arrays, a topic discussed in Chapter 8, so in Figure 2-13 I’ve modified their code a bit to focus on topics covered so far. 30 Chapter 2 Figure 2-13: How the European Space Agency writes the date to its page Everything here should look very familiar to you, except for X and Y, which will make more sense after you’ve read Chapter 3. If anything else in the ESA script seems unclear to you, try doing the homework assignment. In fact, do the homework assignment even if it all seems extremely clear. The only way to really learn JavaScript is to do it. Go ahead, give that homework a shot! And enjoy! Summary This chapter was chock-full of JavaScript goodness. Here’s a review of the most important points for you to understand: z How to declare and use variables (use var the first time and use valid and descriptive variable names) z How to write to web pages with document.write() z How to get the current date from JavaScript with the Date object and its various methods If you got all that, you’re well on your way to becoming a JavaScript superstar. Try the following assignment to test your JavaScript skills. Assignment Change the script in Figure 2-12 so that it writes out the seconds as well as the hour and minutes. If you’re feeling like getting ahead of the game, you can try, for a big chunk of extra credit, to change the time from a 24-hour clock to a 12-hour clock. The getHours() method returns the hour as a number between 0 and 23. See if you can figure out how to adjust that time to be between 1 and 12. You’ll have to use some tricks I haven’t covered in this chapter. If you can’t figure this out now, you’ll be able to do it by the end of the next chapter. U s i n g V a r i a b l e s a n d B u i l t - i n F u n ct i on s to U p d a t e Yo u r W e b P a g e s A ut om a t i c a ll y 31 GIVING THE BROWSERS WHAT THEY WANT Much to the dismay of web developers everywhere, different browsers implement JavaScript and HTML in slightly different ways. Wouldn’t it be great if you could serve each browser exactly the content it could understand? Fortunately, you can use JavaScript to determine which browser a visitor is using. You can then use that information to deliver content suitable for that specific browser, either by redirecting the visitor to a page containing content especially tailored for that browser or by writing your JavaScripts so that the same page does different things depending on the browser looking at it. This chapter covers the three topics you need to understand to deliver browser-specific pages using redirects: z z z How to determine which browser your visitor is using How to redirect the visitor to other pages automatically How to send the visitor to the page you want, depending on which browser he or she is using As in Chapter 2, while learning how to handle an important web authoring task, you’ll also be introduced to fundamental elements of the JavaScript language—in this case, if-then statements and related methods for implementing logical decision making in your scripts. Let’s first talk about determining which browser a visitor is using. A Real-World Example of Browser Detection Before we get into the details of how browser detection works, let’s look at a real-world example. Netscape, the company that brought you the Netscape Navigator browser, has a complicated home page with lots of interesting features. They’ve taken great pains to make their home page look good to most browsers, including early versions of their own browser. If you compare the Netscape home page seen with Netscape Navigator 4 (Figure 3-1) to the page seen using Navigator 8 (Figure 3-2), you’ll notice some subtle differences. Among other things, the news blurb at the bottom of Figure 3-2 has a little navigational element in the lower-right corner. Clicking the numbers in that corner cycles you through different news blurbs. Figure 3-1 does not have these numbers, probably because there isn’t a good way to provide this fancy functionality in the old Netscape Navigator. Figure 3-1: Netscape Navigator 4 view of Netscape home page Figure 3-2: Netscape Navigator 8 view of Netscape home page How does Netscape show the numbers to only those browsers that can provide this feature? There are two steps. First you have to determine which browser your visitor is using. Once you know the browser, you know what JavaScript and HTML features it supports. Then you have to figure out how to control what the person will see based on the known capabilities of the browser. 34 Chapter 3 Browser Detection Methods A browser is identified by its name (Netscape, Firefox, Internet Explorer, and so on) combined with its version number. Your JavaScript needs to determine both of these items. There are two ways to approach this task: a quick but rough method and a slightly less quick but more accurate method. Quick-but-Rough Browser Detection In general, the line var browser_name = navigator.appName; determines who made the browser. If the user is using a Netscape browser, the variable browser_name will be set to the string "Netscape". If it’s a Microsoft Internet Explorer browser, browser_name will be set to "Microsoft Internet Explorer". Every JavaScript-enabled browser must have the variable navigator.appName. If you use Opera, navigator.appName equals "Opera". Unfortunately, some browsers travel incognito. For example, the navigator.appName for Firefox is "Netscape". The JavaScript in Firefox is the same as that for Netscape browsers, so in general, it’s fine to treat Firefox browsers as Netscape browsers. But, as you can see, if you want to be sure about the browser being used, you can’t rely on naviagor.appName. There’s a similar rough method for determining the browser version being used: navigator.appVersion. Unfortunately, navigator.appVersion isn’t just a number but a sometimes cryptic string that varies from browser to browser. For example, the Macintosh browser Safari has this nice, simple navigator.appVersion string: "5.0". By contrast, Internet Explorer 6.0 running under Windows XP has a navigator.appVersion that looks like this: "4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)". To see the navigator.appVersion string for your browser, type this into the browser’s address box (where you normally enter web addresses): javascript:alert(navigator.appVersion) If you care only about whether a person is using a 4.0 browser or later, you can pick out the version numbers from those navigator.appVersion strings with the parseFloat() command, which looks at the string and grabs the first item that resembles a floating-point number (a number that contains a decimal point). Thus the line var browser_version = parseFloat(navigator.appVersion); sets the variable browser_version to the first number in the navigator.appVersion string. For most browsers, this will be the actual version number. For Internet Explorer, it will be 4.0 for any version of the browser 4.0 or later. You can see why I call this method rough. G i v i n g th e B ro w s e r s W h a t T h e y W an t 35 More Accurate Browser Detection JavaScript has another variable that contains information about the browser being used: navigator.userAgent. This variable identifies both the manufacturer of the browser and its version. As it did with navigator.appVersion, however, the formatting of the string varies from browser to browser. Because the navigator.userAgent strings are different from each other, there is no simple way to extract the information you want. Fortunately, people have already written browser sniffers: bits of JavaScript that will do all the hard work of browser identification for you. You can find brwsniff.js, which I downloaded from http://jsbrwsniff.sourceforge.net, at http:// www.bookofjavascript.com/Chapter03. To use this file, put it in the same folder as the web page containing your JavaScript. Then, put this line in the header of your web page: This tells JavaScript to add the contents of the file named brwsniff.js to your web page. Now you can use the JavaScript stored in that file. To use the JavaScript in brwsniff.js to determine the name and version of the browser being used to view your web page, add these lines of JavaScript: X var browser_info = getBrowser(); Y var browser_name = browserInfo[0]; Z var browser_version = browserInfo[1]; Line X calls a function in brwsniff.js that reads the navigator.userAgent string and compares it to all the different browser version strings it knows. Once it determines the name and version of the browser, the function loads this information into a variable called browser_info. All the variables we’ve seen so far store one piece of information—a string or a number, for example. This browser_info variable is an array, a type of variable designed to hold multiple items of related information. You’ll learn how to work with arrays in Chapter 8. For now it’s enough to know that an array is a variable that can store more than one piece of information. Line Y puts the first bit of information stored in the array into a variable called browser_name. Line Z puts the second piece of information stored in browser_info into a variable named browser_version. Used together, these two variables tell you what kind of browser is viewing the web page. Try the web page in Figure 3-3 on your own browser. NOTE This