Wrox Programmer to Programmer™. Join the discussion @ p2p.wrox.com. 4th
Edition. Beginning. JavaScript®. Paul Wilton, Jeremy McPeak. Beginning.
Wilton, McPeak
Step-by-step guidance to creating powerful web apps with JavaScript
•
Covers the various tools needed to create JavaScript web applications
•
Escorts you through selecting a single character from a string, converting character codes to a string, and copying string parts
•
Shows you how to join arrays, copy parts of an array, sort arrays, and reverse an array’s order
•
Explains how using a JavaScript framework (such as jQuery, Prototype, and MooTools) makes JavaScript programming faster and more efficient
•
Offers an in-depth look at Ajax
•
Reviews common mistakes, debugging, and error handling
Paul Wilton owns his own company, providing online booking systems to vacation property owners, which is largely developed using JavaScript. Jeremy McPeak is a self-taught programmer who began his career by tinkering with web sites in 1998. He is the coauthor of Professional Ajax, 2nd Edition and several online articles covering topics such as XSLT, ASP.NET Web Forms, and C#. He is currently employed at an energy-based company building in-house conventional and web applications.
Web Development/JavaScript
525937_cover_2.indd 1
$39.99 USA $47.99 CAN
Programmer Forums Join our Programmer to Programmer forums to ask and answer programming questions about this book, join discussions on the hottest topics in the industry, and connect with fellow programmers from around the world.
Code Downloads Take advantage of free code samples from this book, as well as code samples from hundreds of other books, all ready to use.
Read More Find articles, ebooks, sample chapters and tables of contents for hundreds of books, and more reference resources on programming topics that matter to you.
®
Wrox Beginning guides are crafted to make learning programming languages and technologies easier than you think, providing a structured, tutorial format that will guide you through all the techniques involved.
wrox.com
JavaScript
Walks you through the basics of JavaScript: what it is, how it works, and what you can do with it
Wrox Programmer to Programmer™
Beginning
JavaScript allows you to enhance your web pages and web applications by providing dynamic, personalized, and interactive content. Serving as a great introduction to JavaScript, this book offers all you need to start using JavaScript on your web pages right away. It’s fully updated and covers utilizing JavaScript with the latest versions of the Internet Explorer®, Firefox®, and Safari® browsers. •
Join the discussion @ p2p.wrox.com
4th Edition
Beginning
JavaScript
®
4th Edition
Paul Wilton, Jeremy McPeak 12/18/09 2:29 PM
Related Wrox Books Beginning CSS, 2nd Edition ™
Programmer to Programmer
Get more out of WROX.com
ISBN: 978-0-470-17708-2 Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand designers’ processes from start to finish and gain insight into how designers overcome a site’s unique set of challenges and obstacles. Become comfortable with solving common problems, learn the best practices for using XHMTL with CSS, orchestrate a new look for a blog, tackle browser-compatibility issues, and develop functional navigational structures.
Beginning JavaScript and CSS Development with jQuery ISBN: 978-0-470-22779-4 Beginning JavaScript and CSS Development with jQuery presents the world of dynamic web applications to web developers from the standpoint of modern standards. The author shows new JavaScript developers how working with the standard jQuery library will help them to do more with less code and fewer errors.
Concise Guide to Dojo ISBN: 978-0-470-45202-8 Dojo has rapidly become one of the hottest JavaScript-based web development frameworks. It provides you with the power and flexibility to create attractive and useful dynamic web applications quickly and easily. In this fast-paced, code-intensive guide, you’ll discover how to quickly start taking advantage of Dojo. The pages are packed with useful information and insightful examples that will help you.
JavaScript Programmer’s Reference
Interact
Chapters on Demand
Take an active role online by participating in our P2P forums
Purchase individual book chapters in pdf format
ISBN: 978-0-470-34472-9 Both a tutorial and a reference guide for web developers, employ this complete JavaScript reference to help you understand JavaScript data types, variables, operators, expressions, and statements, work with JavaScript frameworks and data, and improve performance with Ajax.
Professional Ajax, 2nd Edition
Wrox Online Library
Join the Community
Hundreds of our books are available online through Books24x7.com
Sign up for our free monthly newsletter at newsletter.wrox.com
Wrox Blox
Browse
Download short informational pieces and code to keep you up to date and out of trouble!
Ready for more Wrox? We have books and e-books available on .NET, SQL Server, Java, XML, Visual Basic, C#/ C++, and much more!
ISBN: 978-0-470-10949-6 Professional Ajax, 2nd Edition is written for web application developers looking to enhance the usability of their web sites and web applications and intermediate JavaScript developers looking to further understand the language. This second edition is updated to cover Prototype, jQuery, FireBug, Microsoft Fiddler, ASP.NET AJAX Extensions, and much more.
Professional JavaScript for Web Developers, 2nd Edition ISBN: 978-0-470-22780-0 This updated bestseller offers an in-depth look at the JavaScript language and covers such topics as debugging tools in Microsoft Visual Studio, FireBug, and Drosera; client-side data storage with cookies, the DOM, and Flash; client-side graphics with JavaScript including SVG, VML, and Canvas; and design patterns including creational, structural, and behavorial patterns.
Professional JavaScript Frameworks: Prototype, YUI, ExtJS, Dojo and MooTools ISBN: 978-0-470-38459-6 This book offers a selection of some of the most active and most used JavaScript frameworks available, replete with practical examples and explanations of what each framework does best. You’ll look at common web development tasks and discover how each framework approaches that set of tasks, as well as learn how to use the features of each framework and avoid potential pitfalls.
Contact Us. We always like to get feedback from our readers. Have a book idea? Need community support? Let us know by e-mailing
[email protected]
525937_cover_2.indd 2
12/18/09 2:29 PM
Beginning JavaScript ® Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv Chapter 1: Introduction to JavaScript and the Web . . . . . . . . . . . . . . . . . . . . . 1 Chapter 2: Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Chapter 3: Decisions, Loops, and Functions . . . . . . . . . . . . . . . . . . . . . . . . . 51 Chapter 4: Common Mistakes, Debugging, and Error Handling . . . . . . . . . . . 87 Chapter 5: JavaScript — An Object-Based Language . . . . . . . . . . . . . . . . . . 133 Chapter 6: Programming the Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Chapter 7: HTML Forms: Interacting with the User . . . . . . . . . . . . . . . . . . . 219 Chapter 8: Windows and Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Chapter 9: String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Chapter 10: Date, Time, and Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Chapter 11: Storing Information: Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Chapter 12: Dynamic HTML and the W3C Document Object Model . . . . . . . 391 Chapter 13: Using ActiveX and Plug-Ins with JavaScript . . . . . . . . . . . . . . . 469 Chapter 14: Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 Chapter 15: JavaScript Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527 Appendix A: Answers to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591 Appendix B: JavaScript Core Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 Appendix C: W3C DOM Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697 Appendix D: Latin-1 Character Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
25937ffirs.indd i
9/22/09 11:23:54 AM
25937ffirs.indd ii
9/22/09 11:23:54 AM
Beginning JavaScript® Fourth Edition
25937ffirs.indd iii
9/22/09 11:23:54 AM
25937ffirs.indd iv
9/22/09 11:23:54 AM
Beginning JavaScript® Fourth Edition
Paul Wilton Jeremy McPeak
25937ffirs.indd v
9/22/09 11:23:54 AM
Beginning JavaScript® Fourth Edition Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256
www.wiley.com Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-52593-7 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Library of Congress Control Number: 2009933758 Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Sun Microsystems Incorporated. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
25937ffirs.indd vi
9/22/09 11:23:54 AM
In memory of my mum, June Wilton, who in 2006 lost her brave battle against cancer. She was always very proud of me and my books and showed my books to anyone and everyone she happened to meet however briefly and whether they wanted to see them or not! She’s very much missed. — Paul Wilton To my family: Starla, Hayden, and Evan (whom we haven’t yet met in person). To my parents: Jerry and Judy. Thank you all for your love and support. — Jeremy McPeak
25937ffirs.indd vii
9/22/09 11:23:54 AM
25937ffirs.indd viii
9/22/09 11:23:54 AM
About the Authors Paul Wilton started as a Visual Basic applications programmer at the Ministry of Defense in the UK and then found himself pulled into the Net. Having joined an Internet development company, he spent three years helping create Internet solutions. He’s now running his own successful and rapidly growing company developing online holiday property reservation systems. Jeremy McPeak is a self-taught programmer who began his career by tinkering with web sites in 1998. He is the co-author of Professional Ajax, 2nd Edition (Wiley 2007) and several online articles covering topics such as XSLT, ASP.NET WebForms, and C#. He is currently employed in an energy-based company building in-house conventional and web applications. Jeremy can be reached through his web site www.wdonline.com.
25937ffirs.indd ix
9/22/09 11:23:54 AM
25937ffirs.indd x
9/22/09 11:23:54 AM
Credits Acquisitions Editor Scott Meyers
Vice President and Executive Group Publisher Richard Swadley
Project Editor Maureen Spears
Vice President and Executive Publisher Barry Pruett
Technical Editor David M. Karr
Associate Publisher Jim Minatel
Production Editor Rebecca Anderson
Project Coordinator, Cover Lindsay Stanford
Copy Editor C.M. Jones
Compositor Craig Johnson, Happenstance Type-O-Rama
Editorial Director Robyn B. Siesky
Proofreader Kathryn Duggan
Editorial Manager Mary Beth Wakefield
Indexer J & J Indexing
Marketing Manager David Mayhew
Cover Image © Photographer’s Choice/Punchstock
Production Manager Tim Tate
25937ffirs.indd xi
9/22/09 11:23:54 AM
25937ffirs.indd xii
9/22/09 11:23:54 AM
Acknowledgments First, a big thank you to my partner Beci, who, now that the book’s finished, will get to see me for more than 10 minutes a week. I’d also like to say a very big thank you to Maureen Spears, who has worked very efficiently on getting this book into print. Thanks also to Jim Minatel for making this book happen. Many thanks to everyone who’s supported and encouraged me over my many years of writing books. Your help will always be remembered. Finally, pats and treats to my German Shepherd Dog, Katie, who does an excellent job of warding off disturbances from door-to-door salespeople. — Paul Wilton First and foremost, a huge thank you to my wife for putting up with my late nights. Just as huge thanks go to the people at Wiley Publishing: Jim Minatel and Scott Meyers for making this happen; Maureen Spears who was absolutely wonderful to work with in getting this book into its final, printed form; and David M. Karr for keeping me honest. Lastly, thank you Nicholas C. Zakas, author of Professional JavaScript, 2nd Edition (Wiley 2009) and co-author of Professional Ajax, 2nd Edition (Wiley 2007), for getting me into this business. — Jeremy McPeak
25937ffirs.indd xiii
9/22/09 11:23:55 AM
25937ffirs.indd xiv
9/22/09 11:23:55 AM
Contents Introduction Chapter 1: Introduction to JavaScript and the Web Introduction to JavaScript What Is JavaScript? JavaScript and the Web Why Choose JavaScript? What Can JavaScript Do for Me? Tools Needed to Create JavaScript Web Applications
Where Do My Scripts Go? Linking to an External JavaScript File Advantages of Using an External File
Your First Simple JavaScript Programs A Brief Look at Browsers and Compatibility Problems Summary
Chapter 2: Data Types and Variables Types of Data in JavaScript Numerical Data Text Data Boolean Data
Variables — Storing Data in Memory Creating Variables and Giving Them Values Assigning Variables with the Value of Other Variables
Using Data — Calculations and Basic String Manipulation Numerical Calculations Operator Precedence Basic String Operations Mixing Numbers and Strings
Data Type Conversion Dealing with Strings That Won’t Convert
Arrays A Multi-Dimensional Array
Summary Exercise Questions
25937ftoc.indd xv
xxv 1 1 1 2 4 4 5
7 7 8
8 15 16
17 17 18 18 20
20 21 24
26 26 30 34 35
37 40
40 45
49 50
9/22/09 11:02:27 AM
Contents Chapter 3: Decisions, Loops, and Functions Decision Making — The if and switch Statements
51 51
Comparison Operators The if Statement Logical Operators Multiple Conditions Inside an if Statement else and else if Comparing Strings The switch Statement
52 54 58 60 64 66 67
Looping — The for and while Statements
71
The The The The The
for Loop for...in Loop while Loop do...while loop break and continue Statements
Functions Creating Your Own Functions Variable Scope and Lifetime
Summary Exercise Questions
71 74 75 77 78
79 79 83
84 86
Chapter 4: Common Mistakes, Debugging, and Error Handling
87
D’oh! I Can’t Believe I Just Did That: Some Common Mistakes
87
Undefined Variables Case Sensitivity Incorrect Number of Closing Braces Incorrect Number of Closing Parentheses Using Equals (=) Rather than Is Equal To (==) Using a Method as a Property and Vice Versa Missing Plus Signs During Concatenation
Error Handling Preventing Errors The try … catch Statements
Debugging Debugging in Firefox with Firebug Debugging in Internet Explorer Debugging in Safari Using Dragonfly: Opera’s Development Tools
Summary Exercise Questions
88 89 90 90 91 91 92
93 93 94
103 104 116 123 127
131 131
xvi
25937ftoc.indd xvi
9/22/09 11:02:27 AM
Contents Chapter 5: JavaScript — An Object-Based Language
133
Object-Based Programming
133
What Are Objects? Objects in JavaScript Using JavaScript Objects Primitives and Objects
134 134 135 138
JavaScript’s Native Object Types String Objects Array Objects New Array Methods The Math Object Number Object The toFixed() Method Date Objects
Creating New Types of Objects (Reference Types) Summary Exercise Questions
139 139 150 156 160 167 167 168
177 187 188
Chapter 6: Programming the Browser
189
Introduction to the Browser’s Objects
190
The window Object The history Object The location Object The navigator Object The screen Object The document Object Using the document Object The images Collection The links Collection
Responding to the User’s Actions with Events What Are Events? Connecting Code to Events Determining the User’s Browser
Summary Exercise Questions
Chapter 7: HTML Forms: Interacting with the User HTML Forms Other Form Object Properties and Methods HTML Elements in Forms
191 193 194 194 195 195 195 198 199
199 200 200 206
215 217
219 219 222 223
xvii
25937ftoc.indd xvii
9/22/09 11:02:27 AM
Contents Common Properties and Methods Button Elements Text Elements The textarea Element Check Boxes and Radio Buttons Selection Boxes
Summary Exercise Questions
224 226 229 236 239 247
260 262
Chapter 8: Windows and Frames
263
Frames and the window Object
264
Coding Between Frames Code Access Between Frames
268 273
Opening New Windows Opening a New Browser Window Scripting Between Windows Moving and Resizing Windows
Security Summary Exercise Questions
Chapter 9: String Manipulation Additional String Methods The The The The
split() Method replace() Method search() Method match() Method
Regular Expressions Simple Regular Expressions Regular Expressions: Special Characters Covering All Eventualities Grouping Regular Expressions Reusing Groups of Characters
The String Object — split(), replace(), search(), and match() Methods The The The The
split() Method replace() Method search() Method match() Method
284 284 292 297
298 298 299
301 302 302 305 305 306
306 307 315 323 323 325
327 327 329 332 333
xviii
25937ftoc.indd xviii
9/22/09 11:02:27 AM
Contents Using the RegExp Object’s Constructor Telephone Number Validation Validating a Postal Code Validating an E-mail Address Validating a Domain Name
Summary Exercise Questions
Chapter 10: Date, Time, and Timers World Time Setting and Getting a Date Object’s UTC Date and Time
Timers in a Web Page One-Shot Timer Setting a Timer that Fires at Regular Intervals
Summary Exercise Questions
Chapter 11: Storing Information: Cookies
335 339 341 342 342
345 345
347 348 351
358 359 363
364 365
367
Baking Your First Cookie
367
A Fresh-Baked Cookie The Cookie String
368 374
Creating a Cookie Getting a Cookie’s Value Cookie Limitations
377 381 386
A User May Disable Cookies Number and Information Limitation
Cookie Security and IE6+ Summary Exercise Questions
Chapter 12: Dynamic HTML and the W3C Document Object Model The Web Standards HTML XML XHTML ECMAScript
386 387
388 389 389
391 392 394 394 395 396
xix
25937ftoc.indd xix
9/22/09 11:02:27 AM
Contents The Document Object Model The DOM Standard Differences Between the DOM and the BOM Representing the HTML Document as a Tree Structure The Core DOM Objects DOM Objects and Their Properties and Methods
Manipulating the DOM Accessing Elements Changing Appearances Positioning and Moving Content Example: Animated Advertisement DOM Event Handling Event Handling in Internet Explorer
Writing Cross-Browser DHTML JavaScript and XML Manipulating XML with JavaScript Retrieving an XML File in IE Retrieving an XML File in Firefox and Opera Retrieving an XML File (Cross-Browser) Example: Displaying a Daily Message
Summary Exercise Questions
397 397 399 399 402 404
422 422 422 429 432 437 443
447 453 454 454 457 458 459
467 468
Chapter 13: Using ActiveX and Plug-Ins with JavaScript
469
Checking for and Embedding Plug-ins (Non-IE Browsers)
470
Adding a Plug-in to the Page Checking for and Installing Plug-ins
Checking for and Embedding ActiveX Controls on Internet Explorer
470 472
474
Adding an ActiveX Control to the Page Installing an ActiveX Control
475 478
Using Plug-ins and ActiveX Controls
480
Determining Plug-in/ActiveX Control Availability Finishing Up Testing the Disabling of the Form Potential Problems
Summary Exercise Question
481 482 484 485
488 489
xx
25937ftoc.indd xx
9/22/09 11:02:27 AM
Contents Chapter 14: Ajax
491
What Is Ajax?
491
What Can It Do? Browser Support
492 493
Using the XMLHttpRequest Object
494
Cross-Browser Issues Using the XMLHttpRequest Object Asynchronous Requests
494 497 499
Creating a Simple Ajax Module
500
Planning the HttpRequest Module The HttpRequest Constructor Creating the Methods The Full Code
500 501 502 503
Validating Form Fields with Ajax
505
Requesting Information The Received Data Before You Begin
Things to Watch Out For
506 506 506
515
Security Issues Usability Concerns
515 516
Summary Exercise Questions
525 525
Chapter 15: JavaScript Frameworks
527
Picking a Framework to Work With Getting Started
527 528
Installing the Frameworks Testing the Frameworks
529 530
Digging Deeper Into jQuery
537
Selecting Elements Changing Style Creating, Appending, and Removing Elements The jQuery Event Model and Handling Events Rewriting the DHTML Toolbar with jQuery Using jQuery for Ajax
Diving into Prototype Retrieving Elements Manipulating Style Creating, Inserting, and Removing Elements Using Events Rewriting the DHTML Toolbar with Prototype Using Ajax Support
537 539 541 543 545 550
558 558 560 561 562 563 567
xxi
25937ftoc.indd xxi
9/22/09 11:02:27 AM
Contents Delving into MooTools Finding Elements Altering Style Creating, Inserting, and Removing Elements Using and Handling Events Rewriting the DHTML Toolbar with MooTools Ajax Support in MooTools
Summary Exercise Questions
Appendix A: Answers to Exercises Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15
Appendix B: JavaScript Core Reference Browser Reference Reserved Words Other Identifiers to Avoid
JavaScript Operators Assignment Operators Comparison Operators Arithmetic Operators Bitwise Operators Bitwise Shift Operators Logical Operators Miscellaneous Operators Operator Precedence
575 575 576 577 578 579 584
590 590
591 591 593 597 600 604 610 616 624 628 631 634 641 643 653
665 665 666 667
668 668 669 670 671 672 672 673 674
xxii
25937ftoc.indd xxii
9/22/09 11:02:27 AM
Contents JavaScript Statements Block Conditional Declarations Loop Execution Control Statements Exception Handling Statements Other Statements
Top-Level Properties and Functions JavaScript and Jscript Core Objects ActiveXObject Array Boolean Date Function Math Number Object RegExp String
Appendix C: W3C DOM Reference DOM Core Objects Low-Level DOM Objects High-Level DOM Objects
HTML DOM Objects Miscellaneous Objects: The HTML Collection HTML Document Objects: The HTML Document HTML Element Objects HTMLButtonElement
DOM Event Model and Objects EventTarget Event MouseEvent
Miscellaneous Events
675 675 676 676 676 677 677 678
678 679 679 680 682 682 685 687 688 689 690 693
697 697 697 700
705 705 706 707 709
719 719 720 720
722
Appendix D: Latin-1 Character Set
725
Index
733
xxiii
25937ftoc.indd xxiii
9/22/09 11:02:28 AM
25937flast.indd xxiv
9/22/09 11:02:45 AM
Introduction JavaScript is a scripting language that enables you to enhance static web applications by providing dynamic, personalized, and interactive content. This improves the experience of visitors to your site and makes it more likely that they will visit again. You must have seen the flashy drop-down menus, moving text, and changing content that are now widespread on web sites — they are enabled through JavaScript. Supported by all the major browsers, JavaScript is the language of choice on the Web. It can even be used outside web applications — to automate administrative tasks, for example. This book aims to teach you all you need to know to start experimenting with JavaScript: what it is, how it works, and what you can do with it. Starting from the basic syntax, you’ll move on to learn how to create powerful web applications. Don’t worry if you’ve never programmed before — this book will teach you all you need to know, step by step. You’ll find that JavaScript can be a great introduction to the world of programming: with the knowledge and understanding that you’ll gain from this book, you’ll be able to move on to learn newer and more advanced technologies in the world of computing.
Whom This Book Is For To get the most out of this book, you’ll need to have an understanding of HTML and how to create a static web page. You don’t need to have any programming experience. This book will also suit you if you have some programming experience already and would like to turn your hand to web programming. You will know a fair amount about computing concepts, but maybe not as much about web technologies. Alternatively, you may have a design background and know relatively little about the web and computing concepts. For you, JavaScript will be a cheap and relatively easy introduction to the world of programming and web application development. Whoever you are, we hope that this book lives up to your expectations.
What This Book Covers You’ll begin by looking at exactly what JavaScript is, and taking your first steps with the underlying language and syntax. You’ll learn all the fundamental programming concepts, including data and data types, and structuring your code to make decisions in your programs or to loop over the same piece of code many times. Once you’re comfortable with the basics, you’ll move on to one of the key ideas in JavaScript — the object. You’ll learn how to take advantage of the objects that are native to the JavaScript language, such as dates and strings, and fi nd out how these objects enable you to manage complex data and simplify
25937flast.indd xxv
9/22/09 11:02:45 AM
Introduction your programs. Next, you’ll see how you can use JavaScript to manipulate objects made available to you in the browser, such as forms, windows, and other controls. Using this knowledge, you can start to create truly professional-looking applications that enable you to interact with the user. Long pieces of code are very hard to get right every time — even for the experienced programmer — and JavaScript code is no exception. You look at common syntax and logical errors, how you can spot them, and how to use the JavaScript debuggers for Firefox, Internet Explorer, Safari/Chrome, and Opera to aid you with this task. Also, you need to examine how to handle the errors that slip through the net, and ensure that these do not detract from the experience of the end user of your application. From here, you’ll move on to more advanced topics, such as using cookies and jazzing up your web pages with dynamic HTML and XML. Finally, you’ll be looking at a relatively new and exciting technology: Ajax. This allows your JavaScript in a HTML page to communicate directly with a server, and useful for, say, looking up information on a database sitting on your server. If you have the Google toolbar you’ll have seen something like this in action already. When you type a search word in the Google toolbar, it comes up with suggestions, which it gets via the Google search database. Finally, you’ll explore some of the time saving JavaScript frameworks such as jQuery, Prototype, and MooTools and seeing how they work and how they can help you create sophisticated JavaScript powered applications. All the new concepts introduced in this book will be illustrated with practical examples, which enable you to experiment with JavaScript and build on the theory that you have just learned. You’ll find four appendixes at the end of the book. Appendix A provides solutions to the exercises included at the end of most chapters throughout the book. The remaining appendixes contain the reference material that your authors hope you find useful and informational. Appendix B contains the JavaScript language’s core reference. Appendix C contains a complete W3C DOM Core reference — as well as information on the HTML DOM and DOM Level 2 Event model. Appendix D contains the decimal and hexadecimal character codes for the Latin-1 character set.
What You Need to Use This Book Because JavaScript is a text-based technology, all you really need to create documents containing JavaScript is Notepad (or your equivalent text editor). Also, in order to try out the code in this book, you will need a web browser that supports a modern version of JavaScript. Ideally, this means Internet Explorer 8 or later and Firefox 3 or later. The book has been extensively tested with these two browsers. However, the code should work in most modern web browsers, although some of the code in later chapters, where you examine dynamic HTML and scripting the DOM, is specific to particular browsers; but the majority of the code presented is cross-browser. Where there are exceptions, they will be clearly noted.
Conventions To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.
xxvi
25937flast.indd xxvi
9/22/09 11:02:45 AM
Introduction Try It Out The Try It Out is an exercise you should work through, following the text in the book.
1. 2. 3.
It usually consists of a set of steps. Each step has a number. Follow the steps with your copy of the database.
As you work through each Try It Out, the code you’ve typed will be explained in detail. Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.
Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this. As for styles in the text: ❑
We highlight in italic type new terms and important words when we introduce them.
❑
We show keyboard strokes like this: Ctrl+A.
❑
We show file names, URLs, and code within the text like so: persistence.properties.
❑
We present code in two different ways:
Important code in code examples is highlighted with a gray background. The gray highlighting is not used for code that’s less important in the present context, or that has been shown before.
Source Code As you work through the examples in this book, you may choose either to type in all the code manually or to use the source-code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book. Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-52593-7. Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
xxvii
25937flast.indd xxvii
9/22/09 11:02:45 AM
Introduction
Errata We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time you will be helping us provide even higher-quality information. To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml. If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.
p2p.wrox.com For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system on which you can post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums. At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:
1. 2. 3.
Go to p2p.wrox.com and click the Register link.
4.
You will receive an e-mail with information describing how to verify your account and complete the joining process.
Read the terms of use and click Agree. Complete the required information to join as well as any optional information you wish to provide, and click Submit.
You can read messages in the forums without joining P2P, but in order to post your own messages, you must join. Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.
xxviii
25937flast.indd xxviii
9/22/09 11:02:45 AM