JavaScript & JQuery Java Script And J Query The Missing Manual 3rd Edition[A4]
JavaScript%20%26%20jQuery-%20The%20Missing%20Manual%2C%203rd%20Edition
Javascript%20and%20jQuery%20-%20The%20missing%20manual
JavaScript%20%26%20jQuery%20(The%20Missing%20Manual%20-%203rd%20Edition)%20-%20David%20Sawyer%20McFarland%20-%20O'Reilly
JavaScript%20%26%20jQuery-%20The%20Missing%20Manual%2C%203rd%20Edition
JavaScript%20%26%20jQuery-%20The%20Missing%20Manual%2C%203rd%20Edition
User Manual: manual pdf -FilePursuit
Open the PDF directly: View PDF .
Page Count: 686
Download | |
Open PDF In Browser | View PDF |
3rd Edition “The Missing Manual series is simply the most intelligent and usable series of guidebooks…” Answers found here! The important stuff you need to know n ake your pages come alive. Use jQuery to create interactive M elements that respond to visitor input. n et acquainted with jQuery UI. Expand your interface with G tabbed panels, dialog boxes, date pickers, and other widgets. n isplay good forms. Get information from visitors, help D shoppers buy goods, and let members post their thoughts. n o beyond the browser with Ajax. Communicate with the G web server to update your pages without reloading. n ut your new skills right to work. Create a simple application P step-by-step, using jQuery and jQuery UI widgets. n ive into advanced concepts. Use ThemeRoller to customize D your widgets; avoid common errors that new programmers often make. David Sawyer McFarland, president of Sawyer McFarland Media, Inc., has spent nearly 20 years building and managing websites. Having served as webmaster at UC Berkeley, he’s also taught at the UC Berkeley Graduate School of Journalism and the Portland State University multimedia program. David lives in Portland and has written bestselling Missing Manual titles on Adobe Dreamweaver and CSS JavaScript & jQuery n 3rd Editio Covers jQuery UI McFarland Web Authoring and Design US $49.99 JavaScript & jQuery JavaScript lets you supercharge your web pages with animation, interactivity, and visual effects, but learning the language isn’t easy. This fully updated and expanded guide takes you step-by-step through JavaScript basics, then shows you how to save time and effort with jQuery—the library of prewritten JavaScript code—and the newest innovations from the jQuery UI plug-in. —KEVIN KELLY, CO-FOUNDER OF WIRED CAN $52.99 ISBN: 978-1-491-94707-4 missingmanuals.com twitter: @missingmanuals facebook.com/MissingManuals David Sawyer McFarland 3rd Edition “The Missing Manual series is simply the most intelligent and usable series of guidebooks…” Answers found here! The important stuff you need to know n ake your pages come alive. Use jQuery to create interactive M elements that respond to visitor input. n et acquainted with jQuery UI. Expand your interface with G tabbed panels, dialog boxes, date pickers, and other widgets. n isplay good forms. Get information from visitors, help D shoppers buy goods, and let members post their thoughts. n o beyond the browser with Ajax. Communicate with the G web server to update your pages without reloading. n ut your new skills right to work. Create a simple application P step-by-step, using jQuery and jQuery UI widgets. n ive into advanced concepts. Use ThemeRoller to customize D your widgets; avoid common errors that new programmers often make. David Sawyer McFarland, president of Sawyer McFarland Media, Inc., has spent nearly 20 years building and managing websites. Having served as webmaster at UC Berkeley, he’s also taught at the UC Berkeley Graduate School of Journalism and the Portland State University multimedia program. David lives in Portland and has written bestselling Missing Manual titles on Adobe Dreamweaver and CSS JavaScript & jQuery n 3rd Editio Covers jQuery UI McFarland Web Authoring and Design US $49.99 JavaScript & jQuery JavaScript lets you supercharge your web pages with animation, interactivity, and visual effects, but learning the language isn’t easy. This fully updated and expanded guide takes you step-by-step through JavaScript basics, then shows you how to save time and effort with jQuery—the library of prewritten JavaScript code—and the newest innovations from the jQuery UI plug-in. —KEVIN KELLY, CO-FOUNDER OF WIRED CAN $52.99 ISBN: 978-1-491-94707-4 missingmanuals.com twitter: @missingmanuals facebook.com/MissingManuals David Sawyer McFarland JavaScript & jQuery The book that should have been in the box® David Sawyer McFarland Beijing | Cambridge | Farnham | Köln | Sebastopol | Tokyo JavaScript & jQuery: The Missing Manual by David Sawyer McFarland Copyright © 2014 Sawyer McFarland Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 9989938 or corporate@oreilly.com. July 2008: First Edition. October 2011: Second Edition. September 2014: Third Edition. Revision History for the Third Edition: 2014-09-10 First release See http://oreilly.com/catalog/errata.csp?isbn=9781491947074 for release details. The Missing Manual is a registered trademark of O’Reilly Media, Inc. The Missing Manual logo, and “The book that should have been in the box” are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media is aware of a trademark claim, the designations are capitalized. While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions, or for damages resulting from the use of the information contained in it. ISBN-13: 978-1-491-94707-4 [LSI] Contents The Missing Credits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii What Is JavaScript?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii What Is jQuery? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv HTML: The Barebones Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi CSS: Adding Style to Web Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix Software for JavaScript Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii About This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii The Very Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi About the Online Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii Part One: CHAPTER 1: Getting Started with JavaScript Writing Your First JavaScript Program. . . . . . . . . . . . . . . . . . . . . . 3 Introducing Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 How to Add JavaScript to a Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Your First JavaScript Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Writing Text on a Web Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Attaching an External JavaScript File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Tracking Down Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 CHAPTER 2: The Grammar of JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Built-In Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Types of Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Working with Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Tutorial: Using Variables to Create Messages. . . . . . . . . . . . . . . . . . . . . . . . . . 40 Tutorial: Asking for Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Tutorial: Writing to a Web Page Using Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 51 A Quick Object Lesson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 iii CHAPTER 3: Adding Logic and Control to Your Programs. . . . . . . . . . . . . . . 61 Making Programs React Intelligently. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Tutorial: Using Conditional Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Handling Repetitive Tasks with Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Functions: Turn Useful Code Into Reusable Commands. . . . . . . . . . . . . . . . . 85 Tutorial: A Simple Quiz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Part Two: Getting Started with jQuery CHAPTER 4: Introducing jQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 About JavaScript Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Getting jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Adding jQuery to a Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Modifying Web Pages: An Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Understanding the Document Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Selecting Page Elements: The jQuery Way. . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Adding Content to a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Setting and Reading Tag Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Reading, Setting, and Removing HTML Attributes . . . . . . . . . . . . . . . . . . . . . 137 Acting on Each Element in a Selection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Automatic Pull Quotes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 CHAPTER 5: Action/Reaction: Making Pages Come Alive with Events.. 147 What Are Events?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Using Events the jQuery Way. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Tutorial: Introducing Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 More jQuery Event Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Advanced Event Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Tutorial: A One-Page FAQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 CHAPTER 6: Animations and Effects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 jQuery Effects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Tutorial: Login Slider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Animations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Performing an Action After an Effect Is Completed. . . . . . . . . . . . . . . . . . . 194 Tutorial: Animated Dashboard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 jQuery and CSS3 Transitions and Animations . . . . . . . . . . . . . . . . . . . . . . . . 202 CHAPTER 7: Common jQuery Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Swapping Images. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Tutorial: Adding Rollover Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 Tutorial: Photo Gallery with Effects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 Controlling How Links Behave. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 Opening External Links in a New Window . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 iv Contents Creating New Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 Introducing jQuery Plug-ins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 Build a Responsive Navigation Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 CHAPTER 8: Enhancing Web Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Understanding Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Adding Smarts to Your Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Tutorial: Basic Form Enhancements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 Form Validation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Validation Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 Part Three: CHAPTER 9: Getting Started with jQuery UI Expanding Your Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 What Is jQuery UI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 Why Use jQuery UI?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 Using jQuery UI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Adding Messages with Dialog Boxes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Providing Information with Tooltips. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Adding Tabbed Panels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 Saving Space with Accordions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 Adding Menus to a Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 CHAPTER 10: Forms Revisited.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Picking Dates with Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Stylish Select Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360 Styling Buttons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 Improve Radio Buttons and Checkboxes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 Providing Hints with Autocomplete. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 jQuery UI Form Widget Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 CHAPTER 11: Customizing the Look of jQuery UI.. . . . . . . . . . . . . . . . . . . . . . . 385 Introducing ThemeRoller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 Downloading and Using Your New Theme . . . . . . . . . . . . . . . . . . . . . . . . . . . 390 Overriding jQuery UI Styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 CHAPTER 12: jQuery UI Interactions and Effects. . . . . . . . . . . . . . . . . . . . . . . . 399 The Draggable Widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 The Droppable Widget. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 Drag-and-Drop Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 Sorting Page Items. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 jQuery UI Effects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .438 Contents v Part Four: Advanced jQuery and JavaScript CHAPTER 13: Introducing Ajax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 What Is Ajax?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 Ajax: The Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 Ajax the jQuery Way. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 JSON. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 Introducing JSONP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483 Adding a Flickr Feed to Your Site. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484 Tutorial: Adding Flickr Images to Your Site. . . . . . . . . . . . . . . . . . . . . . . . . . . 488 CHAPTER 14: Building a To-Do List Application. . . . . . . . . . . . . . . . . . . . . . . . . 495 An Overview of the Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .495 Add a Button. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 Add a Dialog Box. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498 Adding Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502 Marking Tasks as Complete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508 Deleting Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 Going Further . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515 Part Five: Tips, Tricks, and Troubleshooting CHAPTER 15: Getting the Most from jQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 Useful jQuery Tips and Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 Using the jQuery Docs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 Traversing the DOM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 More Functions for Manipulating HTML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535 CHAPTER 16: Going Further with JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 Working with Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 Finding Patterns in Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 Working with Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562 Dates and Times. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568 Writing More Efficient JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 Putting It All Together. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582 CHAPTER 17: Troubleshooting and Debugging. . . . . . . . . . . . . . . . . . . . . . . . . 587 Top JavaScript Programming Mistakes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 Debugging with the Console. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 Debugging Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609 vi Contents Part Six: APPENDIX A: Appendix JavaScript Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 Basic JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620 jQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620 Advanced JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621 CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623 Contents vii The Missing Credits ABOUT THE AUTHOR David Sawyer McFarland is president of Sawyer McFarland Media, Inc., a web development and training company in Portland, Oregon. He's been building websites since 1995, when he designed his first site—an online magazine for communication professionals. He's served as webmaster at the University of California at Berkeley and the Berkeley Multimedia Research Center, and oversaw a complete CSS-driven redesign of Macworld.com. In addition to building websites, David is also a writer, trainer, and instructor. He's taught web design at UC Berkeley Graduate School of Journalism, the Center for Electronic Art, the Academy of Art College, Ex'Pressions Center for New Media, and Portland State University. He's written articles about the web for Practical Web Design, MX Developer's Journal, Macworld magazine, and CreativePro.com. He welcomes feedback about this book by email: missing@sawmac.com. (If you're seeking technical help, however, please refer to the sources listed in Appendix A.) ABOUT THE CREATIVE TEAM Nan Barber (editor) is associate editor for the Missing Manual series. She lives in Massachusetts with her husband and various electronic devices. Email: nanbarber@ gmail.com. Melanie Yarbrough (production editor) works and plays in Cambridge, Massachusetts, where she bakes up whatever she can imagine and bikes around the city. Email: myarbrough@oreilly.com. Jennifer Davis (technical reviewer) is an engineer with years of experience improving platform development efficiency. As a Chef Automation engineer, she helps companies discover their own best practices to improving workflow reducing mean time to deploy. She is an event organizer for Reliability Engineering, the Bay Area Chef user group. Alex Stangl (technical reviewer) has developed software professionally for 25+ years, using a myriad of languages and technologies. He enjoys challenging problems and puzzles, learning new languages (currently Clojure), doing technical reviews, and being a good dad and husband. Email: alex@stangl.us. Jasmine Kwityn (proofreader) is a freelance copyeditor and proofreader. She lives in New Jersey with her husband, Ed, and their three cats, Mushki, Axle, and Punky. Email: jasminekwityn@gmail.com. THE MISSING CREDITS ix Bob Pfahler (indexer) is a freelance indexer who indexed this book on behalf of Potomac Indexing, LLC, an international indexing partnership at www.potomacindexing.com. Besides the subject of computer technology, he specializes in business, management, biography, and history. Email: bobpfahler@hotmail.com. ACKNOWLEDGMENTS Many thanks to all those who helped with this book, including Jennifer Davis and Alex Stangl, whose watchful eyes saved me from potentially embarrassing mistakes. Thanks also to my many students at Portland State University who have sat through my long JavaScript lectures and struggled through my programming assignments— especially the members of Team Futzbit (Combination Pizza Hut and Taco Bell) for testing the tutorials: Julia Hall, Amber Brucker, Kevin Brown, Josh Elliott, Tracy O'Connor, and Blake Womack. Also, we all owe a big debt of gratitude to John Resig and the jQuery team for creating the best tool yet for making JavaScript fun. Finally, thanks to David Pogue for getting me started; Nan Barber for making my writing sharper and clearer; my wife, Scholle, for putting up with an author's crankiness; and thanks to my kids, Graham and Kate, because they're just awesome. —David Sawyer McFarland THE MISSING MANUAL SERIES Missing Manuals are witty, superbly written guides to computer products that don't come with printed manuals (which is just about all of them). Each book features a handcrafted index and cross-references to specific pages (not just chapters). Recent and upcoming titles include: Access 2010: The Missing Manual by Matthew MacDonald Access 2013: The Missing Manual by Matthew MacDonald Adobe Edge Animate: The Missing Manual by Chris Grover Buying a Home: The Missing Manual by Nancy Conner Creating a Website: The Missing Manual, Third Edition by Matthew MacDonald CSS3: The Missing Manual, Third Edition by David Sawyer McFarland David Pogue's Digital Photography: The Missing Manual by David Pogue Dreamweaver CS6: The Missing Manual by David Sawyer McFarland Dreamweaver CC: The Missing Manual by David Sawyer McFarland and Chris Grover Excel 2010: The Missing Manual by Matthew MacDonald Excel 2013: The Missing Manual by Matthew MacDonald Facebook: The Missing Manual, Third Edition by E. A. Vander Veer FileMaker Pro 13: The Missing Manual by Susan Prosser and Stuart Gripman x THE MISSING CREDITS Flash CS6: The Missing Manual by Chris Grover Galaxy Tab: The Missing Manual by Preston Gralla Galaxy S4: The Missing Manual by Preston Gralla Galaxy S5: The Missing Manual by Preston Gralla Google+: The Missing Manual by Kevin Purdy HTML5: The Missing Manual, Second Edition by Matthew MacDonald iMovie '11 & iDVD: The Missing Manual by David Pogue and Aaron Miller iPad: The Missing Manual, Sixth Edition by J.D. Biersdorfer iPhone: The Missing Manual, Seventh Edition by David Pogue iPhone App Development: The Missing Manual by Craig Hockenberry iPhoto '11: The Missing Manual by David Pogue and Lesa Snider iPod: The Missing Manual, Eleventh Edition by J.D. Biersdorfer and David Pogue Kindle Fire HD: The Missing Manual by Peter Meyers Living Green: The Missing Manual by Nancy Conner Microsoft Project 2010: The Missing Manual by Bonnie Biafore Microsoft Project 2013: The Missing Manual by Bonnie Biafore Motorola Xoom: The Missing Manual by Preston Gralla NOOK HD: The Missing Manual by Preston Gralla Office 2010: The Missing Manual by Nancy Conner and Matthew MacDonald Office 2011 for Macintosh: The Missing Manual by Chris Grover Office 2013: The Missing Manual by Nancy Conner and Matthew MacDonald OS X Mountain Lion: The Missing Manual by David Pogue OS X Mavericks: The Missing Manual by David Pogue OS X Yosemite: The Missing Manual by David Pogue Personal Investing: The Missing Manual by Bonnie Biafore Photoshop CS6: The Missing Manual by Lesa Snider Photoshop CC: The Missing Manual by Lesa Snider Photoshop Elements 12: The Missing Manual by Barbara Brundage PHP & MySQL: The Missing Manual, Second Edition by Brett McLaughlin QuickBooks 2014: The Missing Manual by Bonnie Biafore QuickBooks 2015: The Missing Manual by Bonnie Biafore THE MISSING CREDITS xi Switching to the Mac: The Missing Manual, Mavericks Edition by David Pogue Switching to the Mac: The Missing Manual, Yosemite Edition by David Pogue Windows 7: The Missing Manual by David Pogue Windows 8: The Missing Manual by David Pogue WordPress: The Missing Manual, Second Edition by Matthew MacDonald Your Body: The Missing Manual by Matthew MacDonald Your Brain: The Missing Manual by Matthew MacDonald Your Money: The Missing Manual by J.D. Roth For a full list of all Missing Manuals in print, go to www.missingmanuals.com/library. html. xii THE MISSING CREDITS Introduction T he Web was a pretty boring place in its early days. Web pages were constructed from plain old HTML, so they could display information, and that was about all. Folks would click a link and then wait for a new web page to load. That was about as interactive as it got. These days, most websites are almost as responsive as the programs on a desktop computer, reacting immediately to every mouse click. And it’s all thanks to the subjects of this book—JavaScript and its sidekick, jQuery. What Is JavaScript? JavaScript is a programming language that lets you supercharge your HTML with animation, interactivity, and dynamic visual effects. JavaScript can make web pages more useful by supplying immediate feedback. For example, a JavaScript-powered shopping cart page can instantly display a total cost, with tax and shipping, the moment a visitor selects a product to buy. JavaScript can produce an error message immediately after someone attempts to submit a web form that’s missing necessary information. JavaScript also lets you create fun, dynamic, and interactive interfaces. For example, with JavaScript, you can transform a static page of thumbnail images into an animated slideshow. Or you can do something more subtle like stuff more information on a page without making it seem crowded by organizing content into bite-size panels that visitors can access with a simple click of the mouse (page 326). Or add something useful and attractive, like pop-up tooltips that provide supplemental information for items on your web page (page 321). xiii WHAT IS JAVASCRIPT? Another one of JavaScript’s main selling points is its immediacy. It lets web pages respond instantly to actions like clicking a link, filling out a form, or merely moving the mouse around the screen. JavaScript doesn’t suffer from the frustrating delay associated with server-side programming languages like PHP, which rely on communication between the web browser and the web server. Because it doesn’t rely on constantly loading and reloading web pages, JavaScript lets you create web pages that feel and act more like desktop programs than web pages. If you’ve visited Google Maps (http://maps.google.com), you’ve seen JavaScript in action. Google Maps lets you view a map of your town (or pretty much anywhere else for that matter), zoom in to get a detailed view of streets and bus stops, or zoom out to get a bird’s-eye view of how to get across town, the state, or the nation. While there were plenty of map sites before Google, they always required reloading multiple web pages (usually a slow process) to get to the information you wanted. Google Maps, on the other hand, works without page refreshes—it responds immediately to your choices. The programs you create with JavaScript can range from the really simple (like popping up a new browser window with a web page in it) to full-blown web applications like Google Docs (http://docs.google.com), which lets you create presentations, edit documents, and build spreadsheets using your web browser with the feel of a program running directly on your computer. A Bit of History Invented in 10 days by Brendan Eich at Netscape back in 1995, JavaScript is nearly as old as the Web itself. While JavaScript is well respected today, it has a somewhat checkered past. It used to be considered a hobbyist’s programming language, used for adding less-than-useful effects such as messages that scroll across the bottom of a web browser’s status bar like a stock ticker, or animated butterflies following mouse movements around the page. In the early days of JavaScript, it was easy to find thousands of free JavaScript programs (also called scripts) online, but many of those scripts didn’t work in all web browsers, and at times even crashed browsers. NOTE JavaScript has little to do with the Java programming language. JavaScript was originally named LiveScript, but a quick deal by marketers at Netscape eager to cash in on the success of Sun Microsystem’s then-hot programming language led to this long-term confusion. Don’t make the mistake of confusing the two…especially at a job interview! In the early days, JavaScript also suffered from incompatibilities between the two prominent browsers, Netscape Navigator and Internet Explorer. Because Netscape and Microsoft tried to outdo each other’s browsers by adding newer and (ostensibly) better features, the two browsers often acted in very different ways, making it difficult to create JavaScript programs that worked well in both. NOTE After Netscape introduced JavaScript, Microsoft introduced jScript, their own version of JavaScript included with Internet Explorer. xiv JAVASCRIPT & JQUERY: THE MISSING MANUAL Fortunately, the worst of those days is nearly gone and contemporary browsers like Firefox, Safari, Chrome, Opera, and Internet Explorer 11 have standardized much of the way they handle JavaScript, making it easier to write JavaScript programs that work for most everyone. (There are still a few incompatibilities among current web browsers, so you’ll need to learn a few tricks for dealing with cross-browser problems. You’ll learn how to overcome browser incompatibilities in this book.) WHAT IS JQUERY? In the past several years, JavaScript has undergone a rebirth, fueled by high-profile websites like Google, Yahoo!, and Flickr, which use JavaScript extensively to create interactive web applications. There’s never been a better time to learn JavaScript. With the wealth of knowledge and the quality of scripts being written, you can add sophisticated interaction to your website—even if you’re a beginner. NOTE JavaScript is also known by the name ECMAScript. ECMAScript is the “official” JavaScript specification, which is developed and maintained by an international standards organization called Ecma International: www. ecmascript.org. JavaScript Is Everywhere JavaScript isn’t just for web pages, either. It’s proven to be such a useful programming language that if you learn JavaScript you can create Yahoo! Widgets and Google Apps, write programs for the iPhone, and tap into the scriptable features of many Adobe programs like Acrobat, Photoshop, Illustrator, and Dreamweaver. In fact, Dreamweaver has always offered clever JavaScript programmers a way to add their own commands to the program. In the Yosemite version of the Mac OS X operating system, Apple lets users automate their Macs using JavaScript. In addition, JavaScript is used in many helpful front end web development tools like Gulp.js (which can automatically compress images and CSS and JavaScript files) and Bower (which makes it quick and easy to download common JavaScript libraries like jQuery, jQuery UI, or AngularJS to your computer). JavaScript is also becoming increasingly popular for server-side development. The Node.js platform (a version of Google’s V8 JavaScript engine that runs JavaScript on the server) is being embraced eagerly by companies like Walmart, PayPal, and eBay. Learning JavaScript can even lead to a career in building complex serverside applications. In fact, the combination of JavaScript on the frontend (that is, JavaScript running in a web browser) and the backend (on the web server) is known as full stack JavaScript development. In other words, there’s never been a better time to learn JavaScript! What Is jQuery? JavaScript has one embarrassing little secret: writing it can be hard. While it’s simpler than many other programming languages, JavaScript is still a programming language. And many people, including web designers, find programming difficult. xv HTML: THE BAREBONES STRUCTURE To complicate matters further, different web browsers understand JavaScript differently, so a program that works in, say, Chrome may be completely unresponsive in Internet Explorer 9. This common situation can cost many hours of testing on different machines and different browsers to make sure a program works correctly for your site’s entire audience. That’s where jQuery comes in. jQuery is a JavaScript library intended to make JavaScript programming easier and more fun. A JavaScript library is a complex set of JavaScript code that both simplifies difficult tasks and solves cross-browser problems. In other words, jQuery solves the two biggest JavaScript headaches: complexity and the finicky nature of different web browsers. jQuery is a web designer’s secret weapon in the battle of JavaScript programming. With jQuery, you can accomplish tasks in a single line of code that could take hundreds of lines of programming and many hours of browser testing to achieve with your own JavaScript code. In fact, an in-depth book solely about JavaScript would be at least twice as thick as the one you’re holding; and, when you were done reading it (if you could manage to finish it), you wouldn’t be able to do half of the things you can accomplish with just a little bit of jQuery knowledge. That’s why most of this book is about jQuery. It lets you do so much, so easily. Another great thing about jQuery is that you can add advanced features to your website with thousands of easy-to-use jQuery plug-ins. For example, the jQuery UI plug-in (which you’ll meet on page 299) lets you create many complex user interface elements like tabbed panels, drop-down menus, pop-up date-picker calendars—all with a single line of programming! Unsurprisingly, jQuery is used on millions of websites (http://trends.builtwith.com/ javascript/jQuery). It’s baked right into popular content management systems like Drupal and WordPress. You can even find job listings for “jQuery Programmers” with no mention of JavaScript. When you learn jQuery, you join a large community of fellow web designers and programmers who use a simpler and more powerful approach to creating interactive, powerful web pages. HTML: The Barebones Structure JavaScript isn’t much good without the two other pillars of web design—HTML and CSS. Many programmers talk about the three languages as forming the “layers” of a web page: HTML provides the structural layer, organizing content like pictures and words in a meaningful way; CSS (Cascading Style Sheets) provides the presentational layer, making the content in the HTML look good; and JavaScript adds a behavioral layer, bringing a web page to life so it interacts with web visitors. In other words, to master JavaScript, you need to have a good understanding of both HTML and CSS. xvi JAVASCRIPT & JQUERY: THE MISSING MANUAL NOTE For a full-fledged introduction to HTML and CSS, check out Head First HTML with CSS and XHTML by Elisabeth Robson and Eric Freeman. For an in-depth presentation of the tricky subject of Cascading Style Sheets, pick up a copy of CSS3: The Missing Manual by David Sawyer McFarland (both from O’Reilly). HTML: THE BAREBONES STRUCTURE HTML (Hypertext Markup Language) uses simple commands called tags to define the various parts of a web page. For example, this HTML code creates a simple web page:Hey, I am the title of this web page. Hey, I am some body text on this web page. It may not be exciting, but this example has all the basic elements a web page needs. This page begins with a single line—the document type declaration, or doctype for short—that states what type of document the page is and which standards it conforms to. HTML actually comes in different versions, and you use a different doctype with each. In this example, the doctype is for HTML5; the doctype for an HTML 4.01 or XHTML document is longer and also includes a URL that points the web browser to a file on the Internet that contains definitions for that type of file. In essence, the doctype tells the web browser how to display the page. The doctype can even affect how CSS and JavaScript work. With an incorrect or missing doctype, you may end up banging your head against a wall as you discover lots of cross-browser differences with your scripts. If for no other reason, always include a doctype in your HTML. Historically, there have been many doctypes—HTML 4.01 Transitional, HTML 4.01 Strict, XHTML 1.0 Transitional, XHTML 1.0 Strict—but they required a long line of confusing code that was easy to mistype. HTML5’s doctype——is short, simple, and the one you should use. How HTML Tags Work In the example in the previous section, as in the HTML code of any web page, you’ll notice that most instructions appear in pairs that surround a block of text or other commands. Sandwiched between brackets, these tags are instructions that tell a web browser how to display the web page. Tags are the “markup” part of the Hypertext Markup Language. The starting (opening) tag of each pair tells the browser where the instruction begins, and the ending tag tells it where the instruction ends. Ending or closing tags always include a forward slash (/) after the first bracket symbol (<). For example, the tag xvii HTML: THE BAREBONES STRUCTUREmarks the start of a paragraph, while
marks its end. Some tags don’t have closing tags, like , , and
tags, which consist of just a single tag. For a web page to work correctly, you must include at least these three tags: • The tag appears once at the beginning of a web page (after the doctype) and again (with an added slash) at the end. This tag tells a web browser that the information contained in this document is written in HTML, as opposed to some other language. All of the contents of a page, including other tags, appear between the opening and closing tags. If you were to think of a web page as a tree, the tag would be its root. Springing from the root are two branches that represent the two main parts of any web page—the head and the body. • The head of a web page, surrounded by tags, contains the title of the page. It may also provide other, invisible information (such as search keywords) that browsers and web search engines can exploit. In addition, the head can contain information that’s used by the web browser for displaying the web page and for adding interactivity. You put Cascading Style Sheets, for example, in the head of the document. The head of the document is also where you often include JavaScript programming and links to JavaScript files. • The body of a web page, as set apart by its surrounding tags, contains all the information that appears inside a browser window: headlines, text, pictures, and so on. Within the tag, you commonly find tags like the following: • You tell a web browser where a paragraph of text begins with a(opening paragraph tag), and where it ends with a
(closing paragraph tag). • The tag emphasizes text. If you surround some text with it and its partner tag, , you get boldface type. The HTML snippet Warning! tells a web browser to display the word “Warning!” in bold type. • The tag, or anchor tag, creates a hyperlink in a web page. When clicked, a hyperlink—or link—can lead anywhere on the Web. You tell the browser where the link points by putting a web address inside the tags. For instance, you might type Click here!. The browser knows that when your visitor clicks the words “Click here!” it should go to the Missing Manuals website. The href part of the tag is called an attribute and the URL (the uniform resource locator or web address) is the value. In this example, http://www.missingmanuals.com is the value of the href attribute. xviii JAVASCRIPT & JQUERY: THE MISSING MANUAL CSS: ADDING STYLE TO WEB PAGES UP TO SPEED Validating Web Pages As mentioned on page xvii, a web page’s doctype identifies which type of HTML or XHTML you used to create the web page. The rules differ subtly depending on type: For example, unlike HTML 4.01, XHTML doesn’t let you have an unclosedtag, and requires that all tag names and attributes be lowercase ( not , for example). HTML5 includes new tags and lets you use either HTML or XHTML syntax. Because different rules apply to each variant of HTML, you should always validate your web pages. An HTML validator is a program that makes sure a web page is written correctly. It checks the page’s doctype and then analyzes the code in the page to see whether it matches the rules defined by that doctype. For example, the validator flags mistakes like a misspelled tag name or an unclosed tag. The World Wide Web Consortium (W3C), the organization that’s responsible for many of the technologies used on the Web, has a free online validator at http://validator.w3.org. You can copy your HTML and paste it into a web form, upload a web page, or point the validator to an already existing page on the Web; the validator then analyzes the HTML and reports back whether the page is valid or not. If there are any errors, the validator tells you what the error is and on which line of the HTML file it occurs. Valid HTML isn’t just good form—it also helps to make sure your JavaScript programs work correctly. A lot of JavaScript involves manipulating a web page’s HTML: identifying a particular form field, for example, or placing new HTML (like an error message) in a particular spot. In order for JavaScript to access and manipulate a web page, the HTML must be in proper working order. Forgetting to close a tag, using the same ID name more than once, or improperly nesting your HTML tags can make your JavaScript code behave erratically or not at all. CSS: Adding Style to Web Pages At the beginning of the Web, HTML was the only language you needed to know. You could build pages with colorful text and graphics and make words jump out using different sizes, fonts, and colors. But today, web designers turn to Cascading Style Sheets to add visual sophistication to their pages. CSS is a formatting language that lets you make text look good, build complex page layouts, and generally add style to your site. Think of HTML as merely the language you use to structure a page. It helps identify the stuff you want the world to know about. Tags like
and
denote headlines and assign them relative importance: A heading 1 is more important than a heading 2. The
tag indicates a basic paragraph of information. Other tags provide further structural clues: for example, a
tag identifies a bulleted list (to make a list of recipe ingredients more intelligible, for example). CSS, on the other hand, adds design flair to well-organized HTML content, making it more beautiful and easier to read. Essentially, a CSS style is just a rule that tells a web browser how to display a particular element on a page. For example, you can create a CSS rule to make all
tags appear 36 pixels tall, in the Verdana font, and in orange. CSS can do more powerful stuff, too, like add borders, change margins, and even control the exact placement of a page element. xix CSS: ADDING STYLE TO WEB PAGES When it comes to JavaScript, some of the most valuable changes you make to a page involve CSS. You can use JavaScript to add or remove a CSS style from an HTML tag, or dynamically change CSS properties based on a visitor’s input or mouse clicks. You can even animate from the properties of one style to the properties of another (say, animating a background color changing from yellow to red). For example, you can make a page element appear or disappear simply by changing the CSS display property. To animate an item across the screen, you can change the CSS position properties dynamically using JavaScript. Anatomy of a Style A single style that defines the look of one element is a pretty basic beast. It’s essentially a rule that tells a web browser how to format something—turn a headline blue, draw a red border around a photo, or create a 150-pixel-wide sidebar box to hold a list of links. If a style could talk, it would say something like, “Hey, Browser, make this look like that.” A style is, in fact, made up of two elements: the web page element that the browser formats (the selector) and the actual formatting instructions (the declaration block). For example, a selector can be a headline, a paragraph of text, a photo, and so on. Declaration blocks can turn that text blue, add a red border around a paragraph, position the photo in the center of the page—the possibilities are endless. NOTE Technical types often follow the lead of the W3C and call CSS styles rules. This book uses the terms “style” and “rule” interchangeably. Of course, CSS styles can’t communicate in nice, clear English. They have their own language. For example, to set a standard font color and font size for all paragraphs on a web page, you’d write the following: p { color: red; font-size: 1.5em; } This style simply says, “Make the text in all paragraphs—marked with
tags—red and 1.5 ems tall.” (An em is a unit or measurement that’s based on a browser’s normal text size.) As Figure I-1 illustrates, even a simple style like this example contains several elements: • Selector. The selector tells a web browser which element or elements on a page to style—like a headline, paragraph, image, or link. In Figure I-1, the selector (p) refers to the
tag, which makes web browsers format all
tags using the formatting directions in this style. With the wide range of selectors that CSS offers and a little creativity, you can gain fine control of your pages’ formatting. (Selectors are an important part of using jQuery, so you’ll find a detailed discussion of them starting on page 119.) • Declaration block. The code following the selector includes all the formatting options you want to apply to the selector. The block begins with an opening brace ({) and ends with a closing brace (}). xx JAVASCRIPT & JQUERY: THE MISSING MANUAL • Declaration. Between the opening and closing braces of a declaration, you add one or more declarations, or formatting instructions. Every declaration has two parts, a property and a value, and ends with a semicolon. A colon separates the property name from its value: color : red;. CSS: ADDING STYLE TO WEB PAGES • Property. CSS offers a wide range of formatting options, called properties. A property is a word—or a few hyphenated words—indicating a certain style effect. Most properties have straightforward names like font-size, margin-top, and background-color. For example, the background-color property sets—you guessed it—a background color. NOTE If you need to brush up on your CSS, grab a copy of CSS3: The Missing Manual. • Value. Finally, you get to express your creative genius by assigning a value to a CSS property—by making a background blue, red, purple, or chartreuse, for example. Different CSS properties require specific types of values—a color (like red, or #FF0000), a length (like 18px, 2in, or 5em), a URL (like images/ background.gif ), or a specific keyword (like top, center, or bottom). FIGURE I-1 A style (or rule) is made of two main parts: a selector, which tells web browsers what to format, and a declaration block, which lists the formatting instructions that the browsers use to style the selector. You don’t need to write a style on a single line as pictured in Figure I-1. Many styles have multiple formatting properties, so you can make them easier to read by breaking them up into multiple lines. For example, you may want to put the selector and opening brace on the first line, each declaration on its own line, and the closing brace by itself on the last line, like so: p { color: red; font-size: 1.5em; } It’s also helpful to indent properties, with either a tab or a couple of spaces, to visibly separate the selector from the declarations, making it easy to tell which is which. And finally, putting one space between the colon and the property value is optional, but adds to the readability of the style. In fact, you can put as much white space between the two as you want. For example, color:red, color: red, and color : red all work. xxi SOFTWARE FOR JAVASCRIPT PROGRAMMING Software for JavaScript Programming To create web pages made up of HTML, CSS, and JavaScript, you need nothing more than a basic text editor like Notepad (Windows) or TextEdit (Mac). But after typing a few hundred lines of JavaScript code, you may want to try a program better suited to working with web pages. This section lists some common editors—some free and some you can buy. NOTE There are literally hundreds of tools that can help you create web pages and write JavaScript programs, so the following is by no means a complete list. Think of it as a greatest-hits tour of the most popular programs that JavaScript fans are using today. Free Programs There are plenty of free programs out there for editing web pages and style sheets. If you’re still using Notepad or TextEdit, give one of these a try. Here’s a short list to get you started: • Brackets (Windows, Mac, and Linux, http://brackets.io) is an open source code editor from Adobe. It’s free (there is a commercial version with more features named Edge Code), has many great features including a great live browser preview, and is even written in JavaScript! • Notepad++ (Windows, http://notepad-plus-plus.org) is a coder’s friend. It highlights the syntax of JavaScript and HTML code, and lets you save macros and assign keyboard shortcuts to them so you can automate the process of inserting the code snippets you use most. • HTML-Kit (Windows, www.chami.com/html-kit) is a powerful HTML/XHTML editor that includes lots of useful features, like the ability to preview a web page directly in the program (so you don’t have to switch back and forth between browser and editor), shortcuts for adding HTML tags, and a lot more. • CoffeeCup Free HTML Editor (Windows, www.coffeecup.com/free-editor) is the free version of the commercial ($49) CoffeeCup HTML editor. • TextWrangler (Mac, www.barebones.com/products/textwrangler) is free software that’s actually a pared-down version of BBEdit, the sophisticated, well-known text editor for the Mac. TextWrangler doesn’t have all of BBEdit’s built-in HTML tools, but it does include syntax coloring (highlighting tags and properties in different colors so it’s easy to scan a page and identify its parts), FTP support (so you can upload files to a web server), and more. • Eclipse (Windows, Linux, and Mac, www.eclipse.org) is a free, popular choice among Java Developers, but includes tools for working with HTML, CSS, and JavaScript. A version specifically for JavaScript developers is also available (www.eclipse.org/downloads/packages/eclipse-ide-javascript-web-developers/ indigor), as well as Eclipse plug-ins to add autocomplete for jQuery (http:// marketplace.eclipse.org/category/free-tagging/jquery). xxii JAVASCRIPT & JQUERY: THE MISSING MANUAL • Aptana Studio (Windows, Linux, and Mac, www.aptana.org) is a powerful, free coding environment with tools for working with HTML, CSS, JavaScript, PHP, and Ruby on Rails. ABOUT THIS BOOK • Vim and Emacs are tried and true text editors from the Unix world. They’re included with OS X and Linux, and you can download versions for Windows. They’re loved by serious programmers, but have a steep learning curve for most people. Commercial Software Commercial website development programs range from inexpensive text editors to complete website construction tools with all the bells and whistles: • Atom (Windows and Mac, https://atom.io) is a new kid on the block. It’s not yet available for sale, but the beta version is free for now. Atom is developed by the folks at GitHub (a site for sharing and collaboratively working on projects), and offers a large array of features built specifically for the needs of today’s developers. It features a modular design, which allows for lots of third-party plug-ins that enhance the program’s functionality. • SublimeText (Windows, Mac, and Linux, https://www.sublimetext.com) is a darling of many programmers. This text editor ($70) includes many timesaving features for JavaScript programmers, like “auto-paired characters,” which automatically plops in the second character of a pair of punctuation marks (for example, the program automatically inserts a closing parenthesis after you type an opening parenthesis). • EditPlus (Windows, www.editplus.com) is an inexpensive text editor ($35) that includes syntax coloring, FTP, autocomplete, and other wrist-saving features. • BBEdit (Mac, www.barebones.com/products/bbedit). This much-loved Mac text editor ($99.99) has plenty of tools for working with HTML, XHTML, CSS, JavaScript, and more. It includes many useful web building tools and shortcuts. • Dreamweaver (Mac and Windows, www.adobe.com/products/dreamweaver. html) is a visual web page editor ($399). It lets you see how your page looks in a web browser. The program also includes a powerful text editor for writing JavaScript programs and excellent CSS creation and management tools. Check out Dreamweaver CC: The Missing Manual for the full skinny on how to use this powerful program. About This Book Unlike a piece of software such as Microsoft Word or Dreamweaver, JavaScript isn’t a single product developed by a single company. There’s no support department at JavaScript headquarters writing an easy-to-read manual for the average web developer. While you’ll find plenty of information on sites like Mozilla.org (see, for example, xxiii ABOUT THIS BOOK https://developer.mozilla.org/en/JavaScript/Reference or www.ecmascript.org), there’s no definitive source of information on the JavaScript programming language. Because there’s no manual for JavaScript, people just learning JavaScript often don’t know where to begin. And the finer points regarding JavaScript can trip up even seasoned web pros. The purpose of this book, then, is to serve as the manual that should have come with JavaScript. In this book’s pages, you’ll find step-by-step instructions for using JavaScript to create highly interactive web pages. Likewise, you’ll find good documentation on jQuery at http://api.jquery.com. But it’s written by programmers for programmers, and so the explanations are mostly brief and technical. And while jQuery is generally more straightforward than regular JavaScript programming, this book will teach you fundamental jQuery principles and techniques so you can start off on the right path when enhancing your websites with jQuery. JavaScript & jQuery: The Missing Manual is designed to accommodate readers who have some experience building web pages. You’ll need to feel comfortable with HTML and CSS to get the most from this book, because JavaScript often works closely with HTML and CSS to achieve its magic. The primary discussions are written for advanced-beginner or intermediate computer users. But if you’re new to building web pages, special boxes called Up to Speed provide the introductory information you need to understand the topic at hand. If you’re an advanced web page jockey, on the other hand, keep your eye out for similar shaded boxes called Power Users’ Clinic. They offer more technical tips, tricks, and shortcuts for the experienced computer fan. NOTE This book periodically recommends other books, covering topics that are too specialized or tangential for a manual about using JavaScript. Sometimes the recommended titles are from Missing Manual series publisher O’Reilly Media—but not always. If there’s a great book out there that’s not part of the O’Reilly family, we’ll let you know about it. This Book’s Approach to JavaScript JavaScript is a real programming language: It doesn’t work like HTML or CSS, and it has its own set of (often complicated) rules. It’s not always easy for web designers to switch gears and start thinking like computer programmers, and there’s no one book that can teach you everything there is to know about JavaScript. The goal of JavaScript & jQuery: The Missing Manual isn’t to turn you into the next great programmer (though it might start you on your way). This book is meant to familiarize web designers with the ins and outs of JavaScript and then move on to jQuery so that you can add really useful interactivity to a website as quickly and easily as possible. In this book, you’ll learn the basics of JavaScript and programming; but just the basics won’t make for very exciting web pages. It’s not possible in 500 pages to teach you everything about JavaScript that you need to know to build sophisticated, xxiv JAVASCRIPT & JQUERY: THE MISSING MANUAL interactive web pages. Instead, much of this book will cover the wildly popular jQuery JavaScript library, which, as you’ll soon learn, will liberate you from all of the minute, time-consuming details of creating JavaScript programs that run well across different browsers. ABOUT THIS BOOK You’ll learn the basics of JavaScript, and then jump immediately to advanced web page interactivity with a little help—OK, a lot of help—from jQuery. Think of it this way: You could build a house by cutting down and milling your own lumber, constructing your own windows, doors, and doorframes, manufacturing your own tile, and so on. That do-it-yourself approach is common to a lot of JavaScript books. But who has that kind of time? This book’s approach is more like building a house by taking advantage of already-built pieces and putting them together using basic skills. The end result will be a beautiful and functional house built in a fraction of the time it would take you to learn every step of the process. About the Outline JavaScript & jQuery: The Missing Manual is divided into five parts, each containing several chapters: • Part One starts at the very beginning. You’ll learn the basic building blocks of JavaScript as well as get some helpful tips on computer programming in general. This section teaches you how to add a script to a web page, store and manipulate information, and add smarts to a program so it can respond to different situations. You’ll also learn how to communicate with the browser window, store and read cookies, respond to various events like mouse clicks and form submissions, and modify the HTML of a web page. • Part Two introduces jQuery—the Web’s most popular JavaScript library. Here you’ll learn the basics of this amazing programming tool that will make you a more productive and capable JavaScript programmer. You’ll learn how to select and manipulate page elements, add interaction by making page elements respond to your visitors, and add flashy visual effects and animations. • Part Three covers jQuery’s sister project, jQuery UI. jQuery UI is a JavaScript library of helpful “widgets” and effects. It makes adding common user interface elements like tabbed panels, dialog boxes, accordions, drop-down menus really easy. jQuery UI can help you build a unified-looking and stylish user interface for your next big web application. • Part Four looks at some advanced uses of jQuery and JavaScript. In particular, Chapter 13 covers the technology that single-handedly made JavaScript one of the most glamorous web languages to learn. In this chapter, you’ll learn how to use JavaScript to communicate with a web server so your pages can receive information and update themselves based on information provided by a web server—without having to load a new web page. Chapter 14 guides you step by step in creating a to-do list application using jQuery and jQuery UI. • Part Five takes you past the basics, covering more complex concepts. You’ll learn more about how to use jQuery effectively, as well as delve into advanced xxv THE VERY BASICS JavaScript concepts. This part of the book also helps you when nothing seems to be working: when your perfectly crafted JavaScript program just doesn’t seem to do what you want (or worse, it doesn’t work at all!). You’ll learn the most common errors new programmers make as well as techniques for discovering and fixing bugs in your programs. At the end of the book, an appendix provides a detailed list of references to aid you in your further exploration of the JavaScript programming language. The Very Basics To use this book, and indeed to use a computer, you need to know a few basics. This book assumes that you’re familiar with a few terms and concepts: • Clicking. This book gives you three kinds of instructions that require you to use your computer’s mouse or trackpad. To click means to point the arrow cursor at something on the screen and then—without moving the cursor at all—to press and release the clicker button on the mouse (or laptop trackpad). To right-click means to do the same thing with the right mouse button. To double-click, of course, means to click twice in rapid succession, again without moving the cursor at all. And to drag means to move the cursor while pressing the button. TIP If you’re on a Mac and don’t have a right mouse button, you can accomplish the same thing by pressing the Control key as you click with the one mouse button. When you’re told to c-click something on the Mac, or Ctrl-click something on a PC, you click while pressing the c or Ctrl key (both of which are near the space bar). • Menus. The menus are the words at the top of your screen or window: File, Edit, and so on. Click one to make a list of commands appear, as though they’re written on a window shade you’ve just pulled down. • Keyboard shortcuts. If you’re typing along in a burst of creative energy, it’s sometimes disruptive to have to take your hand off the keyboard, grab the mouse, and then use a menu (for example, to use the Bold command). That’s why many experienced computer mavens prefer to trigger menu commands by pressing certain combinations on the keyboard. For example, in the Firefox web browser, you can press Ctrl-+ (Windows) or c-+ (Mac) to make text on a web page get larger (and more readable). When you read an instruction like “press c-B,” start by pressing the c-key; while it’s down, type the letter B, and then release both keys. • Operating system basics. This book assumes that you know how to open a program, surf the Web, and download files. You should know how to use the Start menu (Windows) and the Dock or Apple menu (Macintosh), as well as the Control Panel (Windows), or System Preferences (Mac OS X). xxvi JAVASCRIPT & JQUERY: THE MISSING MANUAL If you’ve mastered this much information, you have all the technical background you need to enjoy JavaScript & jQuery: The Missing Manual. ABOUT THE ONLINE RESOURCES About→These→Arrows Throughout this book, and throughout the Missing Manual series, you’ll find sentences like this one: “Open the System→Library→Fonts.” That’s shorthand for a much longer instruction that directs you to open three nested folders in sequence, like this: “On your hard drive, you’ll find a folder called System. Open that. Inside the System folder window is a folder called Library; double-click it to open it. Inside that folder is yet another one called Fonts. Double-click to open it, too.” Similarly, this kind of arrow shorthand helps to simplify the business of choosing commands in menus, as shown in Figure I-2. FIGURE I-2 In this book, arrow notations help simplify menu instructions. For example, View→Text Size→Increase is a more compact way of saying, “From the View menu, choose Text Size; from the submenu that then appears, choose Increase.” About the Online Resources This book is designed to get your work onto the Web faster and more professionally; it’s only natural, then, that much of the value of this book also lies on the Web. Online, you’ll find example files so you can get some hands-on experience. You can also communicate with the Missing Manual team and tell us what you love (or hate) about the book. Head over to www.missingmanuals.com, or go directly to one of the following sections. Living Examples As you read the book’s chapters, you’ll encounter a number of living examples—stepby-step tutorials that you can build yourself, using raw materials (like graphics and xxvii ABOUT THE ONLINE RESOURCES half-completed web pages) that you can download from either https://github.com/ sawmac/js3e or from this book’s Missing CD page at www.missingmanuals.com/ cds. You might not gain very much from simply reading these step-by-step lessons while relaxing in your porch hammock, but if you take the time to work through them at the computer, you’ll discover that these tutorials give you unprecedented insight into the way professional designers build web pages. You’ll also find, in this book’s lessons, the URLs of the finished pages, so that you can compare your work with the final result. In other words, you won’t just see pictures of JavaScript code in the pages of the book; you’ll find the actual, working web pages on the Internet. Registration If you register this book at http://oreilly.com, you’ll be eligible for special offers—like discounts on future editions of JavaScript & jQuery: The Missing Manual. Registering takes only a few clicks. To get started, type www.oreilly.com/register into your browser to hop directly to the Registration page. Feedback Got questions? Need more information? Fancy yourself a book reviewer? On our Feedback page, you can get expert answers to questions that come to you while reading, share your thoughts on this Missing Manual, and find groups for folks who share your interest in JavaScript and jQuery. To have your say, go to www.missingmanuals.com/feedback. Errata In an effort to keep this book as up to date and accurate as possible, each time we print more copies, we’ll make any confirmed corrections you’ve suggested. We also note such changes on the book’s website, so you can mark important corrections into your own copy of the book, if you like. Go to http://tinyurl.com/jsjq3-mm to report an error and view existing corrections. Safari® Books Online Safari® Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly. With a subscription, you can read any page and watch any video from our library online. Read books on your cellphone and mobile devices. Access new titles before they’re available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features. xxviii JAVASCRIPT & JQUERY: THE MISSING MANUAL PART Getting Started with JavaScript CHAPTER 1: Writing Your First JavaScript Program CHAPTER 2: The Grammar of JavaScript CHAPTER 3: Adding Logic and Control to Your Programs 1 CHAPTER Writing Your First JavaScript Program 1 By itself, HTML doesn’t have any smarts: It can’t do math, it can’t figure out if someone has correctly filled out a form, and it can’t make decisions based on how a web visitor interacts with it. Basically, HTML lets people read text, look at pictures, watch videos, and click links to move to other web pages with more text, pictures, and videos. In order to add intelligence to your web pages so they can respond to your site’s visitors, you need JavaScript. JavaScript lets a web page react intelligently. With it, you can create smart web forms that let visitors know when they’ve forgotten to include necessary information. You can make elements appear, disappear, or move around a web page (see Figure 1-1). You can even update the contents of a web page with information retrieved from a web server—without having to load a new web page. In short, JavaScript lets you make your websites more engaging, effective, and useful. NOTE Actually, HTML5 does add some smarts to HTML—including basic form validation. But because not all browsers support these nifty additions (and because you can do a whole lot more with forms and JavaScript), you still need JavaScript to build the best, most user-friendly and interactive forms. You can learn more about HTML5 and web forms in Ben Henick’s HTML5 Forms (O’Reilly) and Gaurav Gupta’s Mastering HTML5 Forms (Packt Publishing). 3 INTRODUCING PROGRAMMING FIGURE 1-1 The Interactive Ear (http://www.amplifon. co.uk/interactive-ear/), an interactive guide to human hearing, lets visitors learn about and explore the different parts of the human ear. New information appears in response to mouse movements and clicks. With JavaScript, you can create your own interactive effects. Introducing Programming For a lot of people, the term “computer programming” conjures up visions of superintelligent nerds hunched over keyboards, typing nearly unintelligible gibberish for hours on end. And, honestly, some programming is like that. Programming can seem like complex magic that’s well beyond the average mortal. But many programming concepts aren’t difficult to grasp, and as programming languages go, JavaScript is a good first language for someone new to programming. Still, JavaScript is more complex than either HTML or CSS, and programming often is a foreign world to web designers; so one goal of this book is to help you think more like a programmer. Throughout this book, you’ll learn fundamental programming concepts that apply whether you’re writing JavaScript, ActionScript, or even writing a desktop program using C++. More importantly, you’ll learn how to approach a programming task so you’ll know exactly what you want to do before you start adding JavaScript to a web page. Many web designers are immediately struck by the strange symbols and words used in JavaScript. An average JavaScript program is sprinkled with symbols ({ } [ ] ; , () !=) and full of unfamiliar words (var, null, else if). In many ways, learning 4 JAVASCRIPT & JQUERY: THE MISSING MANUAL a programming language is a lot like learning another language. You need to learn new words, new punctuation, and understand how to put them together so you can communicate successfully. INTRODUCING PROGRAMMING Every programming language has its own set of keywords and characters, and its own set of rules for putting those words and characters together—the language’s syntax. You’ll need to memorize the words and rules of the JavaScript language (or at least keep this book handy as a reference). When learning to speak a new language, you quickly realize that placing an accent on the wrong syllable can make a word unintelligible. Likewise, a simple typo or even a missing punctuation mark can prevent a JavaScript program from working, or trigger an error in a web browser. You’ll make plenty of mistakes as you start to learn to program—that’s just the nature of programming. At first, you’ll probably find JavaScript programming frustrating—you’ll spend a lot of your time tracking down errors you made when typing the script. Also, you might find some of the concepts related to programming a bit hard to follow at first. But don’t worry: If you’ve tried to learn JavaScript in the past and gave up because you thought it was too hard, this book will help you get past the hurdles that often trip up folks new to programming. (And if you do have programming experience, this book will teach you JavaScript’s idiosyncrasies and the unique concepts involved in programming for web browsers.) In addition, this book isn’t just about JavaScript—it’s also about jQuery, the world’s most popular JavaScript library. jQuery makes complex JavaScript programming easier…much easier. So with a little bit of JavaScript knowledge and the help of jQuery, you’ll be creating sophisticated, interactive websites in no time. FREQUENTLY ASKED QUESTION Compiled vs. Scripting Languages JavaScript is called a scripting language. I’ve heard this term used for other languages like PHP and ColdFusion as well. What’s a scripting language? Most of the programs running on your computer are written using languages that are compiled. Compiling is the process of creating a file that will run on a computer by translating the code a programmer writes into instructions that a computer can understand. Once a program is compiled, you can run it on your computer, and because a compiled program has been converted directly to instructions a computer understands, it will run faster than a program written with a scripting language. Unfortunately, compiling a program is a time-consuming process: You have to write the program, compile it, and then test it. If the program doesn’t work, you have to go through the whole process again. A scripting language, on the other hand, is only compiled when an interpreter (another program that can convert the script into something a computer can understand) reads it. In the case of JavaScript, the interpreter is built into the web browser. So when your web browser reads a web page with a JavaScript program in it, the web browser translates the JavaScript into something the computer understands. As a result, a scripting language operates more slowly than a compiled language, because every time it runs, the program must be translated for the computer. Scripting languages are great for web developers: Scripts are generally much smaller and less complex than desktop programs, so the lack of speed isn’t as important. In addition, because they don’t require compiling, creating and testing programs that use a scripting language is a much faster process. Chapter 1: Writing Your First JavaScript Program 5 HOW TO ADD JAVASCRIPT TO A PAGE What’s a Computer Program? When you add JavaScript to a web page, you’re writing a computer program. Granted, most JavaScript programs are much simpler than the programs you use to read email, retouch photographs, and build web pages. But even though JavaScript programs (also called scripts) are simpler and shorter, they share many of the same properties of more complicated programs. In a nutshell, any computer program is a series of steps that are completed in a designated order. Say you want to display a welcome message using the web-page visitor’s name: “Welcome, Bob!” There are several things you’d need to do to accomplish this task: 1. Ask the visitor’s name. 2. Get the visitor’s response. 3. Print (that is, display) the message on the web page. While you may never want to print a welcome message on a web page, this example demonstrates the fundamental process of programming: Determine what you want to do, then break that task down into individual steps. Every time you want to create a JavaScript program, you must go through the process of determining the steps needed to achieve your goal. Once you know the steps, you’ll translate your ideas into programming code—the words and characters that make the web browser behave how you want it to. How to Add JavaScript to a Page Web browsers are built to understand HTML and CSS and convert those languages into a visual display on the screen. The part of the web browser that understands HTML and CSS is called the layout or rendering engine. But most browsers also have something called a JavaScript interpreter. That’s the part of the browser that understands JavaScript and can execute the steps of a JavaScript program. The web browser is usually expecting HTML, so you must specifically tell the browser when JavaScript is coming by using the tag, it knows it’s reached the end of the JavaScript program and can get back to its normal duties. Much of the time, you’ll add the HOW TO ADD JAVASCRIPT TO A PAGE The In fact, web browsers let you leave out the type attribute in HTML 4.01 and XHTML 1.0 files as well—the script will run the same; however, your page won’t validate correctly without the type attribute (see the box on page xix for more on validation). This book uses HTML5 for the doctype, but the JavaScript code will be the same and work the same for HTML 4.01, and XHTML 1. You then add your JavaScript code between the opening and closing You’ll find out what this JavaScript does in a moment. For now, turn your attention to the opening and closing The src attribute of the You can (and often will) attach multiple external JavaScript files to a single web page. For example, you might have created one external JavaScript file that controls a drop-down navigation panel, and another that lets you add a nifty slideshow to a page of photos. On your photo gallery page, you’d want to have both JavaScript programs, so you’d attach both files. Chapter 1: Writing Your First JavaScript Program 9 HOW TO ADD JAVASCRIPT TO A PAGE In addition, you can attach external JavaScript files and add a JavaScript program to the same page like this:
My Web Page FIGURE 1-2 Nike.com’s website uses JavaScript extensively to create a compelling showcase for their products. The home page (top) includes a row of navigation buttons along the top—Men, Women, Kids, and so on—that, when moused over, reveal a panel of additional navigation options. For example, mousing over the Sports button (circled in bottom image) reveals a panel listing different sports that Nike makes products for. Just remember that you must use one set of opening and closing . The code should now look like this: YOUR FIRST JAVASCRIPT PROGRAM In this example, the stuff you just typed is shown in boldface. The two HTML tags are already in the file; make sure you type the code exactly where shown. 5. Launch a web browser and open the hello.html file to preview it. A JavaScript Alert box appears (see Figure 1-3). Notice that the page is blank when the alert appears. (If you don’t see the Alert box, you probably mistyped the code listed in the previous steps. Double-check your typing and read the following Tip.) TIP When you first start programming, you’ll be shocked at how often your JavaScript programs don’t seem to work…at all. For new programmers, the most common cause of nonfunctioning programs is simple typing mistakes. Always double-check to make sure you spelled commands (like alert in the first script) correctly. Also, notice that punctuation frequently comes in pairs (the opening and closing parentheses, and single-quote marks from your first script, for example). Make sure you include both opening and closing punctuation marks when they’re required. 6. Click the Alert box’s OK button to close it. When the Alert box disappears, the web page appears in the browser window. Although this first program isn’t earth-shatteringly complex (or even that interesting), it does demonstrate an important concept: A web browser will run a JavaScript program the moment it reads in the JavaScript code. In this example, the alert() command appeared before the web browser displayed the web page, because the JavaScript code appeared before the HTML in the tag. This concept comes into play when you start writing programs that manipulate the HTML of the web page—as you’ll learn in Chapter 3. Chapter 1: Writing Your First JavaScript Program 13 WRITING TEXT ON A WEB PAGE FIGURE 1-3 The JavaScript Alert box is a quick way to grab someone’s attention. It’s one of the simplest JavaScript commands to learn and use. NOTE Some versions of Internet Explorer (IE) don’t like to run JavaScript programs in web pages that you open directly off your hard drive, for fear that the code might do something harmful. So when you try to preview the tutorial files for this book in Internet Explorer, you might see a message saying that IE has blocked the script. Click “Allow blocked content.” This annoying behavior only applies to web pages you preview from your computer, not to files you put up on a web server. To avoid hitting the “Allow blocked content” button over and over, preview pages in a different web browser, like Chrome or Firefox. Writing Text on a Web Page The script in the previous section popped up a dialog box in the middle of your monitor. What if you want to print a message directly onto a web page using JavaScript? There are many ways to do so, and you’ll learn some sophisticated techniques later in this book. However, you can achieve this simple goal with a built-in JavaScript command, and that’s what you’ll do in your second script: 14 JAVASCRIPT & JQUERY: THE MISSING MANUAL 1. In your text editor, open the file hello2.html . While Like the alert() function, document.write() is a JavaScript command that literally writes out whatever you place between the opening and closing parentheses. In this case, the HTMLHello world!
is added to the page: a paragraph tag and two words. 3. Save the page and open it in a web browser. The page opens and the words “Hello world!” appear below the headline (see Figure 1-4). NOTE The tutorial files you downloaded also include the completed version of each tutorial. If you can’t seem to get your JavaScript working, compare your work with the file that begins with complete_ in the same folder as the tutorial file. For example, the file complete_hello2.html contains a working version of the script you added to file hello2.html. The two scripts you just created may leave you feeling a little underwhelmed with JavaScript…or this book. Don’t worry—this is only the beginning. It’s important to start out with a full understanding of the basics. You’ll be doing some very useful and complicated things using JavaScript in just a few chapters. In fact, in the remainder of this chapter you’ll get a taste of some of the advanced features you’ll be able to add to your web pages after you’ve worked your way through the first two parts of this book. Attaching an External JavaScript File As discussed on page 8, you’ll usually put JavaScript code in a separate file if you want to use the same scripts on more than one web page. You then instruct your web pages to load that file and use the JavaScript inside it. External JavaScript files also come in handy when you’re using someone else’s JavaScript code. In particular, there are collections of JavaScript code called libraries, which provide useful JavaScript programming. Usually, these libraries make it easy to do something that’s normally quite difficult. You’ll learn more about JavaScript libraries on page 105, and, in particular, the JavaScript library this book (and much of the Web) uses—jQuery. Chapter 1: Writing Your First JavaScript Program 15 ATTACHING AN EXTERNAL JAVASCRIPT FILE FIGURE 1-4 Wow. This script may not be something to “document.write” home about—ha, ha, JavaScript humor—but it does demonstrate that you can use JavaScript to add content to a web page, a trick that comes in handy when you want to display messages (like “Welcome back to the site, Dave”) after a web page has downloaded. But for now, you’ll get experience attaching an external JavaScript file to a page, and writing a short program that does something cool: 1. In your text editor, open the file fadeIn.html. This page contains just some simple HTML—a fewtags, a headline, and a couple of paragraphs. You’ll be adding a simple visual effect to the page, which causes all of the content to slowly fade into view. 2. Click in the blank line between the and closing tags near the top of the page, and type: This code links a file named jquery.min.js, which is contained in a folder named _js, to this web page. When a web browser loads this web page, it also downloads the jquery.min.js JavaScript file and runs the code inside it. Next, you’ll add your own JavaScript programming to this page. NOTE The min part means that the file is minimized —a process that removes unneeded whitespace and condenses the code to make the file smaller so that it downloads faster. 16 JAVASCRIPT & JQUERY: THE MISSING MANUAL 3. Press Return to create a new blank line, and then type: ATTACHING AN EXTERNAL JAVASCRIPT FILE This ends the block of JavaScript code. Now you’ll add some programming. 5. Click the empty line between the opening and closing script tags and type: $(document).ready(function() { You’re probably wondering what the heck that is. You’ll find out all the details of this code on page 112, but in a nutshell, this line takes advantage of the programming that’s inside the jquery.min.js file to make sure that the browser executes the next line of code at the right time. 6. Hit return to create a new line, and then type: $('header').hide().slideDown(3000); This line does something magical: It makes the “JavaScript & jQuery The Missing Manual” header first disappear and then slowly slide down onto the page over the course of 3 seconds (or 3,000 milliseconds). How does it do that? Well, that’s part of the magic of jQuery, which makes complex effects possible with just a single line of code. 7. Hit Return one last time, and then type: }); This code closes up the JavaScript code, much as a closing tag indicates the end of a JavaScript program. Don’t worry too much about all those weird punctuation marks—you’ll learn how they work in detail later in the book. The main thing you need to make sure of is to type the code exactly as it’s listed here. One typo, and the program may not work. The final code you added to the page should look like the bolded text in the following: Chapter 1: Writing Your First JavaScript Program 17 TRACKING DOWN ERRORS TIP To make your programming easier to read, it’s a good idea to indent code. Much as you indent HTML tags to show which tags are nested inside of other tags, you can indent lines of code that are inside another block of code. For example, the line of code you added in step 6 is nested inside the code for steps 5 and 7, so hitting Tab or pressing the spacebar a couple of times before typing the code for step 6 can make your code easier to understand (as pictured in the final code listed at the end of step 7). 8. Save the HTML file, and open it in a web browser. You should see the headline—Sliding Down—plus a paragraph and the footer at the bottom of the browser window, followed by the boxes containing “JavaScript & jQuery: The Missing Manual” slowly slide down into place. Change the number 3000 to different values (like 250 and 10000) to see how that changes the way the page works. NOTE If you try to preview this page in Internet Explorer and it doesn’t seem to do anything, you’ll need to click the “Enable blocked content” box that appears at the bottom of the page (see the Note on page 14). As you can see, it doesn’t take a whole lot of JavaScript to do some amazing things to your web pages. Thanks to jQuery, you’ll be able to create sophisticated, interactive websites even if you’re not a programming wizard. However, you’ll find it helps to know the basics of JavaScript and programming. Chapters 2 and 3 will cover the basics of JavaScript to get you comfortable with the fundamental concepts and syntax that make up the language. Tracking Down Errors The most frustrating moment in JavaScript programming comes when you try to view your JavaScript-powered page in a web browser…and nothing happens. It’s one of the most common experiences for programmers. Even experienced programmers often don’t get it right the first time they write a program, so figuring out what went wrong is just part of the game. Most web browsers are set up to silently ignore JavaScript errors, so you usually won’t even see a “Hey, this program doesn’t work!” dialog box. (Generally, that’s a good thing, as you don’t want a JavaScript error to interrupt the experience of viewing your web pages.) So how do you figure out what’s gone wrong? There are many ways to track errors in a JavaScript program. You’ll learn some advanced debugging techniques in Chapter 17, but the most basic method is to consult the web browser. Most web browsers keep track of JavaScript errors and record them in a separate window called an error console. When you load a web page that contains an error, you can then view the console to get helpful information about the error, like which line of the web page it occurred in and a description of the error. 18 JAVASCRIPT & JQUERY: THE MISSING MANUAL Often, you can find the answer to the problem in the error console, fix the JavaScript, and then the page will work. The console helps you weed out the basic typos you make when you first start programming, like forgetting closing punctuation, or mistyping the name of a JavaScript command. You can use the error console in your favorite browser, but because scripts sometimes work in one browser and not another, this section shows you how to turn on the JavaScript console in all major browsers, so you can track down problems in each. TRACKING DOWN ERRORS The Chrome JavaScript Console Google’s Chrome browser is beloved by many a web developer. Its DevTools feature gives you many ways to troubleshoot HTML, CSS, and JavaScript problems. Also, its JavaScript console is a great place to begin tracking down errors in your code. It not only describes the errors it finds, it also identifies the line in your code where each error occurred. To open the JavaScript console, click the Customize menu button (circled in Figure 1-5) and choose Tools→JavaScript Console. Or use the keyboard shortcut Ctrl+Shift+J (Windows) or c-Option-J (Mac). FIGURE 1-5 Click the Customize menu (circled) to access the JavaScript console as well as other helpful tools. Choosing the Developer Tools option is another way to get to the console, as the JavaScript console is part of a larger set of Chrome tools called the Developer Tools (DevTools for short). You’ll learn more about those tools in Chapter 17. After you open the console, you can examine any errors that appear in the current page. For example, in Figure 1-6, the console identifies the error as an “Uncaught SyntaxError: Unexpected token ILLEGAL.” OK, it may not be immediately obvious what that means, but as you encounter (and fix) more errors you’ll get used to these terse descriptions. Basically, a syntax error points to some kind of typographical error—an error with the syntax or language of the program. The “Unexpected token ILLEGAL” part just means that the browser has encountered an illegal character, or (and here’s the tricky part) that there’s a missing character. In this case, looking closely at the code you can see there’s an opening single quote mark before “slow” but no final quote mark. Chapter 1: Writing Your First JavaScript Program 19 TRACKING DOWN ERRORS The console also identifies the name of the file the error is in (complete_slide.html, in this case) and the line number the error occurs (line 10). Click the filename, and Chrome opens the file above the console and briefly highlights the line (see Figure 1-5). TIP Because the error console displays the line number where the error occurred, you may want to use a text editor that can show line numbers. That way, you can easily jump from the error console to your text editor and identify the line of code you need to fix. FIGURE 1-6 Chrome’s JavaScript console identifies errors in your programs. Click the filename listed to the right of the error, and Chrome briefly highlights the page with the error (circled). Unfortunately, there’s a long list of things that can go wrong in a script, from simple typos to complex errors in logic. When you’re just starting out with JavaScript programming, many of your errors will be the simple typographic sort. For example, you might forget a semicolon, quote mark, or parenthesis, or misspell a JavaScript command. You’re especially prone to typos when following examples from a book (like this one). Here are a few common mistakes you might make and the (not-so obvious) error messages you may encounter: • Missing punctuation. As mentioned earlier, JavaScript programming often involves lots of symbol pairs like opening and closing parentheses and brackets. For example, if you type alert('hello';—leaving off the closing parenthesis— you’ll probably get the: “Unexpected token ;” message, meaning that Chrome was expecting something other than the character it’s showing. In this case, it encountered the semicolon instead of the closing parenthesis. 20 JAVASCRIPT & JQUERY: THE MISSING MANUAL • Missing quote marks. A string is a series of characters enclosed by quote marks (you’ll learn about these in greater detail on page 27). For example, ‘hello’ is a string in the code alert('hello');. It’s easy to forget either the opening or closing quote mark. It’s also easy to mix up those quote marks; for instance, by pairing a single-quote with a double quote like this: alert('hello");. In either case, you’ll probably see an “Uncaught SyntaxError: Unexpected token ILLEGAL” error. TRACKING DOWN ERRORS • Misspelling commands. If you misspell a JavaScript command— aler('hello');—you’ll get an error saying that the misspelled command isn’t defined: for example, “Uncaught ReferenceError: aler is not defined ,” if you misspell the alert command. You’ll also encounter problems when you misspell jQuery functions (like the .hide() and .slideDown() functions in the previous tutorial). In this case, you’ll get a different error. For example, if you mistyped “hide” as “hid” in step 6 on page 17, Chrome will give you this error: “Uncaught TypeError: Object [object Object] has no method ‘hid’”. • Syntax error. Occasionally, Chrome has no idea what you were trying to do and provides this generic error message. A syntax error represents some mistake in your code. It may not be a typo, but you may have put together one or more statements of JavaScript in a way that isn’t allowed. In this case, you need to look closely at the line where the error was found and try to figure out what mistake you made. Unfortunately, these types of errors often require experience with and understanding of the JavaScript language to fix. As you can see from the preceding list, many errors you’ll make simply involve forgetting to type one of a pair of punctuation marks—like quote marks or parentheses. Fortunately, these are easy to fix, and as you get more experience programming, you’ll eventually stop making them almost completely (no programmer is perfect). The Internet Explorer Console Internet Explorer provides a sophisticated set of developer tools for not only viewing JavaScript errors, but also analyzing CSS, HTML, and transfers of information over the network. When open, the developer tool window appears in the bottom half of the browser window. Press the F12 key to open the developer tools, and press it again to close them. You’ll find JavaScript errors listed under the Console tab (circled in Figure 1-7). NOTE If you first open a web page and then open the Internet Explorer console, you won’t see any errors (even if there are some). You need to reload the page to see any errors. Once the console is open, you’ll see errors on the pages you visit as they load. IE’s Console displays error messages similar to those described earlier for Chrome. However, sometimes they’re very different. For example, IE’s “Unterminated string constant” is an “Unexpected token ILLEGAL” error in Chrome. Like Chrome, Internet Explorer identifies the line of code in the HTML file where the error occurred, which you can click to see the actual code where the error occurs. Chapter 1: Writing Your First JavaScript Program 21 TRACKING DOWN ERRORS FIGURE 1-7 The Internet Explorer developer tools provide access to JavaScript errors that occur on a page, as well as a whole lot of other information. The Firefox JavaScript Web Console Mozilla’s Firefox browser also gives you a console to view JavaScript errors. To open the JavaScript console, on Windows click the Firefox tab in the top left of the browser window and choose Web Developer→Web Console. On a Mac, select Tools→Web Developer→Web Console. Or use the keyboard shortcuts Ctrl+Shift+I (Windows) or c-Option-K (Mac). Once the console opens, you’ll see any JavaScript errors on the page. Unfortunately, Firefox’s Web Console is more like a fire hose of data than a simple JavaScript error reporter (Figure 1-8). That’s because it provides information on all sorts of things: files downloaded, CSS and HTML errors, and more. NOTE The Firebug plug-in (http://getfirebug.com) greatly expands on Firefox’s Error Console. In fact, it provided the model for the developer tools in Internet Explorer, Chrome, and Safari (discussed next). 22 JAVASCRIPT & JQUERY: THE MISSING MANUAL TRACKING DOWN ERRORS FIGURE 1-8 If you don’t want to see all of the messages in Firefox’s Web Console, just click the button for the type of message you wish to hide. For example, click the CSS button to hide CSS error messages, the Security button to hide security warnings, and so on. You’ll know if the button is disabled because it looks lighter gray, like the CSS and Security buttons here. A button is enabled when it’s darker and looks like it has been pressed “in,” like the Net, JS (short for JavaScript), and Logging buttons here. The Safari Error Console Safari’s error console is available from the Develop menu: Develop→Show Error Console (or, if you’re on a Mac, use the Option-c-C keyboard shortcut). However, the Develop menu isn’t normally turned on when Safari is installed, so there are a couple of steps to get to the JavaScript console. To turn on the Develop menu, you need to first access the Preferences window. Choose Safari→Preferences. Once the Preferences window opens, click the Advanced button. Turn on the “Show Develop menu in menu bar” box and close the Preferences window. When you restart Safari, the Develop menu will appear between the Bookmarks and Window menus in the menu bar at the top of the screen. Select Develop→Show Error Console to open the console (see Figure 1-9). Chapter 1: Writing Your First JavaScript Program 23 TRACKING DOWN ERRORS FIGURE 1-9 The Safari Error Console displays the name of the JavaScript error, the filename (and location), and the line on which Safari encountered the error. Each tab or browser window has its own error console, so if you’ve already opened the console for one tab, you need to choose Develop→Show Error Console again if you wish to see an error for another tab or window. In addition, if you reload a page, Safari doesn’t clear any prior errors on that page, so you can end up with a long list of old, fixed errors as you work on a page and reload it. The answer: click the Trash icon (circled) to remove the list of old errors, and then reload the page. NOTE If you’re on Windows, you may have an old version of the Safari browser. Apple has stopped updating Safari for Windows, so the Safari information shown here may not apply to you. 24 JAVASCRIPT & JQUERY: THE MISSING MANUAL CHAPTER The Grammar of JavaScript 2 L earning a programming language is a lot like learning any new language: you need to learn new words and punctuation, as well as master a new set of rules. And just as you need to learn the grammar of French to speak French, you must become familiar with the grammar of JavaScript to program JavaScript. This chapter covers the concepts that all JavaScript programs rely on. If you’ve had any experience with JavaScript programming, many of these concepts may be old hat, so you might just skim this chapter. But if you’re new to JavaScript, or you’re still not sure about the fundamentals, this chapter introduces you to basic (but crucial) topics. Statements A JavaScript statement is a basic programming unit, usually representing a single step in a JavaScript program. Think of a statement as a sentence: Just as you string sentences together to create a paragraph (or a chapter, or a book), you combine statements to create a JavaScript program. In the previous chapter, you saw several examples of statements. For example: alert('Hello world!'); This single statement opens an alert window with the message “Hello World!” In many cases, a statement is a single line of code. Each statement ends with a semicolon—it’s like a period at the end of a sentence. The semicolon makes it clear that the step is over and that the JavaScript interpreter should move on to the next action. When you’re writing a JavaScript program, you generally type a statement, enter a 25 BUILT-IN FUNCTIONS semicolon, press Return to create a new line, type another statement, followed by a semicolon, and so on until the program is complete. NOTE As you see more advanced examples of JavaScript (like later in this book), you’ll realize that semicolons don’t always go at the end of every line. A semicolon sometimes won’t appear until after many lines of code. Nonetheless, those multiple lines still form a single statement—just think of them as one, really long statement with lots of different punctuation (kind of like this sentence). Officially, putting a semicolon even at the end of every statement is optional, and some programmers leave it out to make their code shorter. Don’t be one of them. Leaving off the semicolon makes reading your code more difficult and, in some cases, causes JavaScript errors. If you want to make your JavaScript code more compact so that it downloads more quickly, see page 585. Built-In Functions JavaScript (and web browsers) lets you use various commands to make things happen in your programs and on your web pages. These commands, called functions, are like verbs in a sentence. They get things done. For example, the alert() function you encountered earlier makes the web browser open a dialog box and display a message. Some functions, like alert() or document.write(), which you encountered on page 15, are specific to web browsers. In other words, they only work with web pages, so you won’t find them when programming in other environments that use JavaScript (like Node.js, Adobe Photoshop, or Flash’s JavaScript-based ActionScript). Other functions are universal to JavaScript and work anywhere JavaScript works. For example, isNaN() is a function that checks to see whether a particular value is a number—this function comes in handy when you want to see if a visitor has correctly supplied a number for a question that requires a numerical answer (for example, “How many widgets would you like?”). You’ll learn more about how to use isNaN()on page 564. You’ll learn many JavaScript functions throughout this book. One quick way to identify a function is by the parentheses. For example, you can tell isNaN() is a function because of the parentheses following isNaN. In addition, JavaScript lets you create your own functions, so you can make your scripts do things beyond what the standard JavaScript commands offer. You’ll learn about functions in Chapter 3, starting on page 85. NOTE 26 Sometimes you’ll hear people refer to a JavaScript function as a method. JAVASCRIPT & JQUERY: THE MISSING MANUAL Types of Data TYPES OF DATA You deal with different types of information every day. Your name, the price of food, the address of your doctor’s office, and the date of your next birthday are all information that is important to you. You make decisions about what to do based on this information. Computer programs are no different. They also rely on information to get things done. For example, to calculate the total for a shopping cart, the program needs to know the price and quantity of each item ordered. To customize a web page with a visitor’s name (“Welcome Back, Kotter”), the program needs to know the name. Programming languages usually categorize information into different types, and treat each type in a different way. In JavaScript, the three most basic types of data are number, string, and Boolean. Numbers Numbers are used for counting and calculating; you can keep track of the number of days until summer vacation, or calculate the cost of buying two tickets to a movie. Numbers are very important in JavaScript programming: You can use numbers to keep track of how many times a visitor has visited a web page, to specify the exact pixel position of an item on a web page, or to determine how many products a visitor wants to order. In JavaScript, a number is represented by a numeric character; 5, for example, is the number five. You can also use fractional numbers with decimals, like 5.25 or 10.3333333. JavaScript even lets you use negative numbers, like –130 or -459.67. Because numbers are frequently used for calculations, your programs will often include mathematical operations. You’ll learn about operators on page 33, but just to provide an example of using JavaScript with numbers, say you wanted to print the total value of 5 plus 15 on a web page; you could do that with this line of code: document.write(5 + 15); This snippet of JavaScript adds the two numbers together and prints the total (20) onto a web page. There are many different ways to work with numbers, and you’ll learn more about them starting on page 33. Strings To display a name, a sentence, or any series of letters, you use strings. A string is just a series of characters (letters and other symbols) enclosed inside of quote marks. For example, 'Welcome, Hal', and "You are here" are both examples of strings. You used a string in Chapter 1 with the alert command—alert('Hello World!'). A string’s opening quote mark tells the JavaScript interpreter that what follows is a string—just a series of symbols. The interpreter accepts the symbols literally, rather than trying to interpret the string as anything special to JavaScript like a command. When the interpreter encounters the final quote mark, it understands that it has reached the end of the string and continues onto the next part of the program. Chapter 2: The Grammar of JavaScript 27 TYPES OF DATA You can use either double quote marks ("hello world") or single quote marks ('hello world') to enclose the string, but you must make sure to use the same type of quote mark at the beginning and end of the string (for example, "this is not right' isn’t a valid string because it begins with a double-quote mark and ends with a single-quote). So, to pop-up an alert box with the message Warning, warning! you could write: alert('Warning, warning!'); or alert("Warning, warning!"); You’ll use strings frequently in your programming—when adding alert messages, when dealing with user input on web forms, and when manipulating the contents of a web page. They’re so important that you’ll learn a lot more about using strings starting on page 36. FREQUENTLY ASKED QUESTION Putting Quotes into Strings When I try to create a string with a quote mark in it, my program doesn’t work. Why? Likewise, you can use double quotes to enclose a string that has a single quote inside it: "This isn't fair", for example. In JavaScript, quote marks indicate the beginning and end of a string, even when you don’t want them to. When the JavaScript interpreter encounters the first quote mark, it says to itself, “Ahh, here comes a string.” When it reaches a matching quote mark, it figures it has come to the end of the string. That’s why you can’t create a string like this: "He said, "Hello."". In this case, the first quote mark (before the word “He”) marks the start of the string, but as soon as the JavaScript interpreter encounters the second quote mark (before the word “Hello”), it figures that the string is over, so you then end up with the string “ He said,” then the Hello. part, and then another, empty string created by the two quote marks at the end. This code creates a JavaScript error, and your program won’t work. Another method is to tell the JavaScript interpreter to just treat the quote mark inside the string literally—that is, treat the quote mark as part of the string, not the end of the string. You do this using an escape character. If you precede the quote mark with a backward slash (\), JavaScript treats the quote as part of the string. So, you could rewrite the example like this: "He said, \"Hello.\"". In some cases, an escape character is the only choice. For example: 'He said, "This isn\'t fair."'. Because the string is enclosed by single quotes, the lone single quote in the word “isn’t” has to have a backward slash before it: isn\’t . There are a couple of ways to get around this conundrum. The easiest method is to use single quotes to enclose a string that has one or more double quotes inside it. For example, 'He said, "Hello."' is a valid string—the single quotes create the string, and the double quotes inside are a part of the string. 28 You can even escape quote marks when you don’t necessarily have to—as a way to make it clear that the quote mark should be taken literally. For example, 'He said, \"Hello.\"'. Even though you don’t need to escape the double quotes (because single quotes surround the entire string), some programmers do it anyway so it’s clear to them that the quote mark is just a quote mark. JAVASCRIPT & JQUERY: THE MISSING MANUAL Booleans Whereas numbers and strings offer almost limitless variations, the Boolean data type is simple. It is either one of two values: true or false. You’ll encounter Boolean data types when you create JavaScript programs that respond intelligently to user input and actions. For example, if you want to make sure a visitor supplied an email address before submitting a form, you can add logic to your page by asking the simple question: “Did the user type a valid email address?” The answer to this question is a Boolean value: Either the email address is valid (true) or it’s not (false). Depending on the answer to the question, the page could respond in different ways. For example, if the email address is valid (true), then submit the form; if it is not valid (false), then display an error message and prevent the form from being submitted. VARIABLES In fact, Boolean values are so important that JavaScript includes two special keywords to represent those values: true and false You’ll learn how Boolean values come into play when adding logic to your programs in the box on page 66. Variables You can type a number, string, or Boolean value directly into your JavaScript program, but these data types work only when you already have the information you need. For example, you can make the string “Hi, Bob” appear in an alert box like this: alert('Hi, Bob'); But that statement only makes sense if everyone who visits the page is named Bob. If you want to present a personalized message for different visitors, the name needs to be different depending on who is viewing the page: “Hi, Mary,” “Hi, Joseph,’’ “Hi, Ezra,” and so on. Fortunately, all programming languages provide a tool called a variable to deal with just this kind of situation. A variable is a way to store information so you can later use and manipulate it. For example, imagine a JavaScript-based pinball game where the goal is to get the highest score. When a player first starts the game, her score will be 0, but as she knocks the pinball into targets, the score will get bigger. In this case, the score is a variable because it starts at 0 but changes as the game progresses—in other words, a variable holds information that can change with the circumstances. See Figure 2-1 for an example of another game that uses variables. Think of a variable as a kind of basket: You can put an item into a basket, look inside the basket, dump out the contents of a basket, or even replace what’s inside the Chapter 2: The Grammar of JavaScript 29 VARIABLES basket with something else. However, even though you might change what’s inside the basket, the basket itself remains the same. FIGURE 2-1 Super Spice Dash (http:// mcbites.sh75.net) uses JavaScript to create a Super Monkey Ball-like game to promote McDonalds Spicy Chicken McBites. You maneuver a Chicken McBite (no joke) through a course, collecting golden crumbs and chilies while avoiding obstacles and jumping over gaps in the road. As you play, your score is tracked in the upper-right corner. This game uses a variable to keep track of the score, as its value changes as the game goes on. Creating a Variable In JavaScript, to create a variable named score, you would type: var score; The first part, var, is a JavaScript keyword that creates, or, in programming-speak, declares the variable. The second part of the statement, score, is the variable’s name. What name you use is up to you, but there are a few rules you must follow when naming variables: • Variable names must begin with a letter, $, or _. In other words, you can’t begin a variable name with a number or punctuation: so 1thing, and &thing won’t work, but score, $score, and _score are fine. • Variable names can only contain letters, numbers, $, and _. You can’t use spaces or any other special characters anywhere in the variable name: fish&chips and fish and chips aren’t legal, but fish_n_chips and plan9 are. • Variable names are case-sensitive. The JavaScript interpreter sees uppercase and lowercase letters as distinct, so a variable named SCORE is different from a variable named score, which is also different from variables named sCoRE and Score. 30 JAVASCRIPT & JQUERY: THE MISSING MANUAL • Avoid keywords. Some words in JavaScript are specific to the language itself: var, for example, is used to create a variable, so you can’t name a variable var. In addition, some words, like alert, document, and window, are considered special properties of the web browser. You’ll end up with a JavaScript error if you try to use those words as variable names. You can find a list of some reserved words in Table 2-1. Not all of these reserved words will cause problems in all browsers, but it’s best to steer clear of these names when naming variables. VARIABLES TABLE 2-1 Some words are reserved for use by JavaScript and the web browser. Avoid using them as variable names. JAVASCRIPT KEYWORDS RESERVED FOR FUTURE USE RESERVED FOR BROWSER break abstract alert case boolean blur catch byte closed continue char document debugger class focus default const frames delete double history do enum innerHeight else export innerWidth false extends length finally final location for float navigator function goto open if implements outerHeight in import outerWidth instanceof int parent new interface screen null let screenX return long screenY switch native statusbar this package window throw private true protected try public typeof short var static Chapter 2: The Grammar of JavaScript 31 VARIABLES JAVASCRIPT KEYWORDS RESERVED FOR FUTURE USE void super while synchronized with throws RESERVED FOR BROWSER transient volatile yield In addition to these rules, aim to make your variable names clear and meaningful. Naming variables according to what type of data you’ll be storing in them makes it much easier to look at your programming code and immediately understand what’s going on. For example, score is a great name for a variable used to track a player’s game score. The variable name s would also work, but the single letter “s” doesn’t give you any idea about what’s stored in the variable. Likewise, make your variable names easy to read. When you use more than one word in a variable name, either use an underscore between words or capitalize the first letter of each word after the first. For example, imagepath isn’t as easy to read and understand as image_path or imagePath. Using Variables Once you declare a variable, you can store any type of data you’d like in it. To do so, you use the = sign. For example, to store the number 0 in a variable named score, you could type this code: var score; score = 0; The first line of this code creates the variable; the second line stores the number 0 in that variable. The equals sign is called an assignment operator, because it’s used to assign a value to a variable. You can also create a variable and store a value in it with a single JavaScript statement like this: var score = 0; You can store strings, numbers, and Boolean values in a variable: var var var var 32 firstName = 'Peter'; lastName = 'Parker'; age = 22; isSuperHero = true; JAVASCRIPT & JQUERY: THE MISSING MANUAL NOTE To save typing, you can declare multiple variables with a single var keyword, like this: WORKING WITH DATA TYPES AND VARIABLES var x, y, z; You can even declare and store values into multiple variables in one JavaScript statement: var isSuperHero=true, isAfraidOfHeights=false; Once you’ve stored a value in a variable, you can access that value simply by using the variable’s name. For example, to open an alert dialog box and display the value stored in the variable score, you’d type this: alert(score); Notice that you don’t use quotes with a variable—that’s just for strings; so the code alert('score') will display the word “score” and not the value stored in the variable score. Now you can see why strings have to be enclosed in quote marks: The JavaScript interpreter treats words without quotes as either special JavaScript objects (like the alert() command) or as variable names. NOTE You should only use the var keyword once for each variable—when you first create the variable. After that, you’re free to assign new values to the variable without using var. Working with Data Types and Variables Storing a particular piece of information like a number or string in a variable is usually just a first step in a program. Most programs also manipulate data to get new results. For example, you can add a number to a score to increase it, multiply the number of items ordered by the cost of the item to get a sub total, or personalize a generic message by adding a name to the end: “Good to see you again, Igor.” JavaScript provides various operators to modify data. An operator is a symbol or word that can change one or more values into something else. For example, you use the + sign—the addition operator—to add numbers together. There are different types of operators for the different data types. Basic Math JavaScript supports basic mathematical operations such as addition, division, subtraction, and so on. Table 2-2 shows the most basic math operators and how to use them. Chapter 2: The Grammar of JavaScript 33 WORKING WITH DATA TYPES AND VARIABLES TABLE 2-2 Basic math with JavaScript OPERATOR WHAT IT DOES HOW TO USE IT + Adds two numbers 5 + 25 - Subtracts one number from another 25 - 5 * Multiplies two numbers 5 * 10 / Divides one number by another 15/5 FREQUENTLY ASKED QUESTION Spaces, Tabs, and Carriage Returns in JavaScript JavaScript seems so sensitive about typos. How do I know when I’m supposed to use space characters, and when I’m not allowed to? In general, JavaScript is pretty relaxed about spaces, carriage returns, and tabs. You can often leave out spaces or even add extra spaces and carriage returns without a problem. JavaScript interpreters ignore extra spaces, so you’re free to insert extra spaces, tabs, and carriage returns to format your code. For example, you don’t need a space on either side of an assignment operator, but you can add them if you find it easier to read. Both of the following lines of code work: var formName='signup'; var formRegistration = 'newsletter' ; In fact, you can insert as many spaces as you’d like, and even insert carriage returns within a statement. So both of the following statements also work: var formName = 'signup'; var formRegistration = 'newsletter'; Of course, just because you can insert extra space, doesn’t mean you should. The last two examples are actually harder to read and understand because of the extra space. So the general rule of thumb is to add extra space if it makes your code easier to understand. For example, extra carriage returns help make code easier to read when declaring and setting the value of multiple variables at once. The following code is a single line: However, some programmers find it easier to read if each variable is on its own line: var score=0, highScore=0, player=''; Whether you find this spacing easier to read is up to you; the JavaScript interpreter just ignores those line breaks. You’ll see examples of how space can make code easier to read with JavaScript object literals (page 136) and with arrays (page 44). There are a couple of important exceptions to these rules. For example, you can’t insert a carriage return inside a string; in other words, you can’t split a string over two lines in your code like this: var name = 'Bob Smith'; Inserting a carriage return (pressing the Enter or Return key) like this produces a JavaScript error and your program won’t run. In addition, you must put a space between keywords: varscore=0, for example, is not the same as var score=0. The latter example creates a new variable named “score,” while the former stores the value 0 in a variable named “varscore.” The JavaScript interpreter needs the space between var and score to identify the var keyword: var score=0. However, a space isn’t necessary between keywords and symbols like the assignment operator (=) or the semicolon that ends a statement. var score=0, highScore=0, player=''; 34 JAVASCRIPT & JQUERY: THE MISSING MANUAL You may be used to using an x for multiplication (4 x 5, for example), but in JavaScript, you use the * (asterisk) to multiply two numbers. WORKING WITH DATA TYPES AND VARIABLES You can also use variables in mathematical operations. Because a variable is only a container for some other value like a number or string, using a variable is the same as using the contents of that variable. Here’s an example: var price = 10; var itemsOrdered = 15; var totalCost = price * itemsOrdered; The first two lines of code create two variables (price and itemsOrdered) and store a number in each. The third line of code creates another variable (totalCost) and stores the results of multiplying the value stored in the price variable (10) and the value stored in the itemsOrdered variable. In this case, the total (150) is stored in the variable totalCost. This sample code also demonstrates the usefulness of variables. Suppose you write a program as part of a shopping cart system for an e-commerce website. Throughout the program, you need to use the price of a particular product to make various calculations. You could code the actual price throughout the program (for example, say the product cost $10, so you’d type 10 in each place in the program that price is used). However, if the price ever changes, you’d have to locate and change each line of code that uses the price. By using a variable, on the other hand, you can set the price of the product somewhere near the beginning of the program. Then, if the price ever changes, you only need to modify the one line of code that defines the product’s price to update the price throughout the program: var price = 20; var itemsOrdered = 15; var totalCost = price * itemsOrdered; There are lots of other ways to work with numbers (you’ll learn a bunch starting on page 562), but you’ll find that you most frequently use the basic math operators listed in Table 2-2. The Order of Operations If you perform several mathematical operations at once—for example, if you add up several numbers and then multiply them all by 10—you need to keep in mind the order in which the JavaScript interpreter performs its calculations. Some operators take precedence over other operators, so they’re calculated first. This fact can cause some unwanted results if you’re not careful. Take this example: 4 + 5 * 10 You might think this is simply calculated from left to right: 4 + 5 is 9 and 9 * 10 is 90. It’s not. The multiplication actually goes first, so this equation works out to 5 * 10 is 50, plus 4 is 54. Multiplication (the * symbol) and division (the / symbol) take precedence over addition (+) and subtraction (–). Chapter 2: The Grammar of JavaScript 35 WORKING WITH DATA TYPES AND VARIABLES To make sure that the math works out the way you want it, use parentheses to group operations. For example, you could rewrite the equation above like this: (4 + 5) * 10 Any math that’s performed inside parentheses happens first, so in this case the 4 is added to 5 first and the result, 9, is then multiplied by 10. If you want the multiplication to occur first, it would be clearer to write that code like this: 4 + (5*10); Combining Strings Combining two or more strings to make a single string is a common programming task. For example, if a web page has a form that collects a person’s first name in one form field and his last name in a different field, you need to combine the two fields to get his complete name. What’s more, if you want to display a message letting the user know his form information was submitted, you need to combine the generic message with the person’s name: “John Smith, thanks for your order.” Combining strings is called concatenation, and you accomplish it with the + operator. Yes, that’s the same + operator you use to add number values, but with strings it behaves a little differently. Here’s an example: var firstName = 'John'; var lastName = 'Smith'; var fullName = firstName + lastName; In the last line of the code above, the contents of the variable firstName are combined (or concatenated) with the contents of the variable lastName. The two are literally joined together and the result is placed in the variable fullName. In this example, the resulting string is “JohnSmith”—there isn’t a space between the two names, as concatenating just fuses the strings together. In this case (and many others), you need to add an empty space between strings that you intend to combine: var firstName = 'John'; var lastName = 'Smith'; var fullName = firstName + ' ' + lastName; The ' ' in the last line of this code is a single quote, followed by a space, followed by a final single quote. This code is simply a string that contains an empty space. When placed between the two variables in this example, it creates the string “John Smith”. This last example also demonstrates that you can combine more than two strings at a time; in this case, three strings. NOTE Remember that a variable is just a container that can hold any type of data, like a string or number. So when you combine two variables with strings (firstName + lastName), it’s the same as joining two strings like this: 'John' + 'Smith'. 36 JAVASCRIPT & JQUERY: THE MISSING MANUAL Combining Numbers and Strings Most of the mathematical operators only make sense for numbers. For example, it doesn’t make any sense to multiply 2 and the string “eggs”. If you try this example, you’ll end up with a special JavaScript value NaN, which stands for “not a number.” However, there are times when you may want to combine a string with a number. For example, say you want to present a message on a web page that specifies how many times a visitor has been to your website. The number of times she’s visited is a number, but the message is a string. In this case, you use the + operator to do two things: convert the number to a string and concatenate it with the other string. Here’s an example: WORKING WITH DATA TYPES AND VARIABLES var numOfVisits = 101; var message = 'You have visited this site ' + numOfVisits + ' times.'; In this case, message contains the string “You have visited this site 101 times.” The JavaScript interpreter recognizes that there is a string involved, so it realizes it won’t be doing any math (no addition). Instead, it treats the + as the concatenation operator, and at the same time realizes that the number should be converted to a string as well. This example may seem like a good way to print words and numbers in the same message. In this case, it’s obvious that the number is part of a string of letters that makes up a complete sentence, and whenever you use the + operator with a string value and a number, the JavaScript interpreter converts the number to a string. That feature, known as automatic type conversion, can cause problems, however. For example, if a visitor answers a question on a form (“How many pairs of shoes would you like?”) by typing a number (2, for example), that input is treated like a string—'2'. So you can run into a situation like this: var numOfShoes = '2'; var numOfSocks = 4; var totalItems = numOfShoes + numOfSocks; You’d expect the value stored in totalItems to be 6 (2 shoes + 4 pairs of socks). Instead, because the value in numOfShoes is a string, the JavaScript interpreter converts the value in the variable numOfSocks to a string as well, and you end up with the string '24' in the totalItems variable. There are a couple of ways to prevent this error. First, you add + to the beginning of the string that contains a number like this: var numOfShoes = '2'; var numOfSocks = 4; var totalItems = +numOfShoes + numOfSocks; Chapter 2: The Grammar of JavaScript 37 WORKING WITH DATA TYPES AND VARIABLES Adding a + sign before a variable (making sure there’s no space between the two) tells the JavaScript interpreter to try to convert the string to a number value—if the string only contains numbers, like '2', you’ll end up with the string converted to a number. In this example, you end up with 6 (2 + 4). Another technique is to use the Number() command like this: var numOfShoes = '2'; var numOfSocks = 4; var totalItems = Number(numOfShoes) + numOfSocks; Number() converts a string to a number if possible. (If the string is just letters and not numbers, you get the NaN value to indicate that you can’t turn letters into a number.) In general, you’ll most often encounter numbers as strings when getting input from a visitor; for example, when retrieving a value a visitor entered into a form field. So, if you need to do any addition using input collected from a form or other source of visitor input, make sure you run it through the Number() command first. NOTE This problem only occurs when adding a number to a string that contains a number. If you try to multiply the numOfShoes variable with a variable containing a number—shoePrice, for example—the JavaScript interpreter will convert the string in numOfShoes to a number and then multiply it by the shoePrice variable. Changing the Values in Variables Variables are useful because they can hold values that change as the program runs—a score that changes as a game is played, for example. So how do you change a variable’s value? If you just want to replace what’s contained inside a variable, assign a new value to the variable. For example: var score = 0; score = 100; However, you’ll frequently want to keep the value that’s in the variable and just add something to it or alter it in some way. For example, with a game score, you never just set a new score—you add or subtract from the current score. To add to the value of a variable, you use the variable’s name as part of the operation, like this: var score = 0; score = score + 100; That last line of code may appear confusing at first, but it uses a very common technique. Here’s how it works: All of the action happens to the right of the = sign first; that is, the score + 100 part. Translated, it means “take what’s currently stored in score (0) and then add 100 to it.” The result of that operation is then stored back into the variable score. The final outcome of these two lines of code is that the variable score now has the value of 100. 38 JAVASCRIPT & JQUERY: THE MISSING MANUAL The same logic applies to other mathematical operations like subtraction, division, and multiplication: WORKING WITH DATA TYPES AND VARIABLES score = score - 10; score = score * 10; score = score / 10; In fact, performing math on the value in a variable and then storing the result back into the variable is so common that there are shortcuts for doing so with the main mathematical operations, as pictured in Table 2-3. TABLE 2-3 Shortcuts for performing math on a variable OPERATOR WHAT IT DOES HOW TO USE IT THE SAME AS += Adds value on the right side of equals sign to the variable on the left. score += 10 score = score + 10 -= Subtracts value on the right side of the equals sign from the variable on the left. score -= 10 score = score - 10 *= Multiplies the variable on the left side of the equals sign and the value on the right side of the equals sign. score *= 10 score = score * 10 /= Divides the value in the variable by the value on the right side of the equals sign. score /= 10 score = score / 10 ++ Placed directly after a variable name, ++ adds 1 to the variable. score++ score = score + 1 -- Placed directly after a variable name, -- subtracts 1 from the variable. score-- score = score - 1 The same rules apply when concatenating a string to a variable. For example, say you have a variable with a string in it and want to add another couple of strings onto that variable: var name = 'Franklin'; var message = 'Hello'; message = message + ' ' + name; As with numbers, there’s a shortcut operator for concatenating a string to a variable. The += operator adds the string value to the right of the = sign to the end of the variable’s string. So you could rewrite the last line of the above code like this: message += ' ' + name; You’ll see the += operator frequently when working with strings, and throughout this book. Chapter 2: The Grammar of JavaScript 39 TUTORIAL: USING VARIABLES TO CREATE MESSAGES Tutorial: Using Variables to Create Messages In this tutorial, you’ll use variables to print (that is, write) a message onto a web page. NOTE To follow along with the tutorials in this chapter, you need to download the tutorial files from this book’s companion website. See the Note on page 12 for details. 1. In a text editor, open the file use_variable.html in the chapter02 folder. This page is just a basic HTML file with a simple CSS-enhanced design. It doesn’t yet have any JavaScript. You’ll use variables to write a message onto a web page. 2. Locate thetag (a little over half way down the file) and add the opening and closing This HTML should be familiar by now: It simply sets the page up for the script you’re about to write. NOTE This page uses the HTML5 doctype. If you’re using XHTML 1.0 or HTML 4.01, add type="javascript" to the 7. Preview the page in a web browser to enjoy the fruits of your labor (see Figure 2-2). The words “Cookie Monster” should appear below the headline “Using a Variable.” If you don’t see anything, there’s probably a typo in your code. Compare the script above with what you typed and check page 18 for tips on debugging a script using Firefox, Safari, Chrome, or IE 9. 8. Return to your text editor and change the second line of the script to read: var lastName = 'Jar'; Save the page and preview it in a web browser. Voilà! The message now reads: Cookie Jar. (The file complete_use_variable.html has a working copy of this script.) Chapter 2: The Grammar of JavaScript 41 TUTORIAL: ASKING FOR INFORMATION FIGURE 2-2 While writing “Cookie Monster” may not be the reason you picked up a book on JavaScript, this script does demonstrate an important concept: how to create and use variables in JavaScript. Tutorial: Asking for Information In the last script, you saw how to create variables, but you didn’t get to experience how variables let a program respond to the user and produce unique, customized content. In this next tutorial, you’ll learn how to use the prompt() command to gather input from a user and change the display of the page based on that input. 1. In a text editor, open the file prompt.html in the chapter02 folder. To make your programming go faster, the file already has the 42 JAVASCRIPT & JQUERY: THE MISSING MANUAL The prompt() function produces a dialog box similar to one from the alert() function. However, instead of just displaying a message, the prompt() function can also retrieve an answer. In addition, to use the prompt() function, you supply two strings separated by a comma between the parentheses. Figure 2-3 shows what happens to those two strings: The first string appears as the dialog box’s question (in this example, “What is your name?”). TUTORIAL: ASKING FOR INFORMATION FIGURE 2-3 The prompt() function is one way to retrieve user input. It works by providing two strings to the function—one to appear as the question, and another that pre-fills the prompt box with text. The second string appears in the field the visitor types into. This example uses what’s called an empty string, which is just two double quote marks ("") and results in a blank text field (as discussed on page 28, you can use either single or double quote marks for strings). However, you can supply a useful instruction like “Please type both your first and last names” for the second string, and it will appear in the field. Unfortunately, a visitor must first delete that text from the text field before entering his own information. The prompt() function returns a string containing whatever the visitor types into the dialog box. In this line of JavaScript code, that result is stored into a new variable named name. NOTE Many functions return a value. In other words, the function supplies some information after it’s done. You can choose to ignore this information or store it into a variable for later use. In this example, the prompt() function returns a string that you store in the variable name. 3. Save the page and preview it in a web browser. When the page loads, you’ll see a dialog box. Notice that nothing else happens—you don’t even see the web page—until you fill out the dialog box and click OK. You’ll also notice that nothing much happens after you click OK—that’s because, at this point, you’ve merely collected and stored the response; you haven’t used that response on the page. You’ll do that next. Chapter 2: The Grammar of JavaScript 43 ARRAYS 4. Return to your text editor. Locate the second set of Here you take advantage of the information supplied by the visitor. As with the script on page 41, you’re combining several strings—an opening paragraph tag and text, the value of the variable, and a closing paragraph tag—and printing the results to the web page. 5. Save the page and preview it in a web browser. When the Prompt dialog box appears, type in a name and click OK. Notice that the name you type appears in the web page (Figure 2-4). Reload the web page and type a new name—it changes! Just like a good variable should. FIGURE 2-4 The power of variables: This page customizes its message based on a visitor’s response. Arrays Simple variables, like the ones you learned about in the previous section, hold only one piece of information, such as a number or a string value. They’re perfect when you only need to keep track of a single thing like a score, an age, or a total cost. However, if you need to keep track of a bunch of related items—like the names of all of the days in a week, or a list of all of the images on a web page—simple variables aren’t very convenient. 44 JAVASCRIPT & JQUERY: THE MISSING MANUAL For example, say you’ve created a JavaScript shopping cart system that tracks items a visitor intends to buy. If you wanted to keep track of all of the items the visitor adds to her cart using simple variables, you’d have to write code like this: ARRAYS var item1 = 'Xbox 360'; var item2 = 'Tennis shoes'; var item3 = 'Gift certificate'; But what if she wanted to add more items than that? You’d have to create more variables—item4, item5, and so on. And, because you don’t know how many items the visitor might want to buy, you really don’t know how many variables you’ll have to create. Fortunately, JavaScript provides a better method of tracking a list of items, called an array. An array is a way of storing more than one value in a single place. Think of an array like a shopping list. When you need to go to the grocery store, you sit down and write a list of items to buy. If you just went shopping a few days earlier, the list might only contain a few items, but if your cupboard is bare, your shopping list might be quite long. Regardless of how many items are on the list, though, there’s still just a single list. Without an array, you have to create a new variable for each item in the list. Imagine, for example, that you couldn’t make a list of groceries on a single sheet of paper, but had to carry around individual slips of paper—one for each item that you’re shopping for. If you wanted to add another item to buy, you’d need a new slip of paper; then you’d need to keep track of each slip as you shopped (see Figure 2-5). That’s how simple variables work. But with an array, you can create a single list of items, and even add, remove, or change items at any time. FIGURE 2-5 An array provides a simple, organized way to track a list of related items. Adding another item to the list is just like writing a new item at the bottom of the list. Chapter 2: The Grammar of JavaScript 45 ARRAYS Creating an Array To create and store items in an array, you first declare the array’s name (just as you would a variable) and then supply a list of comma-separated values: each value represents one item in the list. As with variables, what you name your array is up to you, but you need to follow the same naming rules listed on page 38. To create an array, you put the list of items between opening and closing brackets: [ ]. For example, to create an array containing abbreviations for the seven days of the week, you could write this code: var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; The brackets are very important—they tell the JavaScript interpreter that it’s dealing with an array. You can create an empty array without any elements like this: var playList = []; Creating an empty array is the equivalent of declaring a variable, as described on page 29. You’ll create an empty array when you don’t add items to the array until the program is running. For example, the above array might be used to track songs that someone selects from a list on a web page. You don’t know ahead of time which songs the person will choose, so you declare an empty array and later fill it with items as the person selects music. (Adding items to an array is described on page 48.) NOTE When looking through other people’s JavaScript programs (or other JavaScript books), you may encounter another way to create an array using the Array keyword, like this: var days = new Array('Mon', 'Tues', 'Wed'); This method is valid, but the method used in this book (called an array literal) is preferred by the pros because it requires less typing, less code, and is considered more “elegant.” You can store any mix of values in an array. In other words, numbers, strings, and Boolean values can all appear in the same array: var prefs = [1, -30.4, 'www.oreilly.com', false]; NOTE You can even store arrays and other objects as elements inside an array. This technique can help store complex data. The array examples above show the array created on a single line. However, if you’ve got a lot of items to add, or the items are long strings, trying to type all of that on a single line can make your program difficult to read. Another option many programmers use is to create an array over several lines, like this: var authors = [ 'Ernest Hemingway', 'Charlotte Bronte', 'Dante Alighieri', 'Emily Dickinson' ]; 46 JAVASCRIPT & JQUERY: THE MISSING MANUAL As mentioned in the box on page 34, a JavaScript interpreter skips extra space and line breaks, so even though this code is displayed on five lines, it’s still just a single statement, as indicated by the final semicolon on the last line. ARRAYS TIP To make the names line up as above, you’d type the first line—var authors = [ 'Ernest Hemingway',—hit Return, then press the space key as many times as it takes to line up the next value, 'Charlotte Bronte'. Accessing Items in an Array You can access the contents of a simple variable just by using the variable’s name. For example, alert(lastName) opens an alert box with the value stored in the variable lastName. However, because an array can hold more than one value, you can’t just use its name alone to access the items it contains. A number, called an index, indicates the position of each item in an array. To access a particular item in an array, you use that item’s index number. For example, say you’ve created an array with abbreviations for the days of the week, and want to open an alert box that displayed the first item. You could write this: var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; alert(days[0]); This code opens an alert box with ‘Mon’ in it. Arrays are zero-indexed, meaning that the first item in an array has an index value of 0, and the second item has an index value of 1. In other words, subtract one from the item’s spot in the list to get its index value—the fifth item’s index is 5 minus 1 (that is, 4). Zero-indexing is pretty confusing when you first get started with programming, so Table 2-4 shows how the array days (from the above example) is indexed, as well as the values it contains and how to access each value. TABLE 2-4 Items in an array must be accessed using an index number equivalent to their place in the list minus 1 INDEX VALUE ITEM TO ACCESS ITEM 0 Mon days[0] 1 Tues days[1] 2 Wed days[2] 3 Thurs days[3] 4 Fri days[4] 5 Sat days[5] 6 Sun days[6] You can change the value of an item in an array by assigning a new value for that index position. For example, to put a new value into the first item in the array days, you could write this: days[0] = 'Monday'; Chapter 2: The Grammar of JavaScript 47 ARRAYS Because the index number of the last item in an array is always one less than the total number of items in an array, you only need to know how many items are in an array to access the last item. Fortunately, this is an easy task because every array has a length property, which contains the total number of items in the array. To access the length property, add a period followed by length after the array’s name: For example, days.length returns the number of items in the array named days (if you created a different array, playList, for example, you’d get its length like this: playList.length). So you can use this tricky bit of JavaScript to access the value stored in the last item in the array: days[days.length-1] This last snippet of code demonstrates that you don’t have to supply a literal number for an index (for example, the 0 in days[0]). You can also supply an equation that returns a valid number. In this case, days.length – 1 is actually a short equation: It first retrieves the number of items in the days array (that’s 7 in this example) and subtracts 1 from it. So, in this case, days[days.length-1] translates to days[6]. You can also use a variable containing a number as the index: var i = 0; alert(days[i]); The last line of code is the equivalent of alert(days[0]);. You’ll find this technique particularly useful when working with loops, as described in the next chapter (page 80). Adding Items to an Array Say you’ve created an array to track items that a user clicks on a web page. Each time the user clicks the page, an item is added to the array. JavaScript supplies several ways to add contents to an array. ADDING AN ITEM TO THE END OF AN ARRAY To add an item to the end of an array, you can use the index notation from page 47, using an index value that’s one greater than the last item in the list. For example, say you’ve created an array named properties: var properties = ['red', '14px', 'Arial']; At this point, the array has three items. Remember that the last item is accessed using an index that’s one less than the total number of items, so in this case, the last item in this array is properties[2]. To add another item, you could do this: properties[3] = 'bold'; This line of code inserts 'bold' into the fourth spot in the array, which creates an array with four elements: ['red', '14px', 'Arial', 'bold']. When you add the new item, you use an index value that’s equal to the total number of elements currently in the array, so you can be sure you’re always adding an item to the end of 48 JAVASCRIPT & JQUERY: THE MISSING MANUAL an array by using the array’s length property as the index. For example, you can rewrite the last line of code like this: ARRAYS properties[properties.length] = 'bold'; You can also use an array’s push() command, which adds whatever you supply between the parentheses to the end of the array. As with the length property, you apply push() by adding a period to the array’s name followed by push(). For example, here’s another way to add an item to the end of the properties array: properties.push('bold'); Whatever you supply inside the parentheses (in this example, the string 'bold') is added as a new item at the end of the array. You can use any type of value, like a string, number, Boolean, or even a variable. One advantage of the push() command is that it lets you add more than one item to the array. For example, say you want to add three values to the end of an array named properties, you could do that like this: properties.push('bold', 'italic', 'underlined'); ADDING AN ITEM TO THE BEGINNING OF AN ARRAY If you want to add an item to the beginning of an array, use the unshift() command. Here’s an example of adding the bold value to the beginning of the properties array: var properties = ['red', '14px', 'Arial']; properties.unshift('bold'); After this code runs, the array properties contains four elements: ['bold', 'red', '14px', 'Arial']. As with push(), you can use unshift() to insert multiple items at the beginning of an array: properties.unshift('bold', 'italic', 'underlined'); NOTE Make sure you use the name of the array followed by a period and the method you wish to use. In other words, push('new item') won’t work because the JavaScript interpreter doesn’t know which array it should add that item to. You must first use the array’s name (whatever name you gave the array when you created it) followed by a period, and then the method, like this: authors.push('Stephen King');. CHOOSING HOW TO ADD ITEMS TO AN ARRAY So far, this chapter has shown you three ways to add items to an array. Table 2-5 compares these techniques. Each of these commands accomplishes similar tasks, so the one you choose depends on the circumstances of your program. If the order that the items are stored in the array doesn’t matter, then any of these methods work. For example, say you have a page of product pictures, and clicking one picture adds the product to a shopping cart. You use an array to store the cart items. The order the items appear in the cart (or the array) doesn’t matter, so you can use any of these techniques. Chapter 2: The Grammar of JavaScript 49 ARRAYS However, if you create an array that keeps track of the order in which something happens, then the method you choose does matter. For example, say you’ve created a page that lets visitors create a playlist of songs by clicking song names on the page. Because a playlist lists songs in the order they should be played, the order is important. So if each time the visitor clicks a song, the song’s name should go at the end of the playlist (so it will be the last song played), then use the push() method. TABLE 2-5 Various ways of adding elements to an array METHOD ORIGINAL ARRAY EXAMPLE CODE RESULTING ARRAY .length property var p = [0,1,2,3] p[p.length]=4 [0,1,2,3,4] Adds one value to the end of an array. push() var p = [0,1,2,3] p.push(4,5,6) [0,1,2,3,4,5,6] Adds one or more items to the end of an array. unshift() var p = [0,1,2,3] p.unshift(4,5) [4,5,0,1,2,3] Adds one or more items to the beginning of an array. EXPLANATION The push() and unshift() commands return a value. To be specific, once push() and unshift() complete their tasks, they supply the number of items that are in the array. Here’s an example: var p = [0,1,2,3]; var totalItems = p.push(4,5); After this code runs, the value stored in totalItems is 6, because there are six items in the p array. Deleting Items from an Array If you want to remove an item from the end or beginning of an array, use the pop() or shift() commands. Both commands remove one item from the array: The pop() command removes the item from the end of the array, while shift() removes one item from the beginning. Table 2-6 compares the two methods. TABLE 2-6 Two ways of removing an item from an array ORIGINAL ARRAY EXAMPLE CODE RESULTING ARRAY pop() var p = [0,1,2,3] p.pop() [0,1,2] Removes the last item from the array. shift() var p = [0,1,2,3] p.shift() [1,2,3] Removes the first item from the array. METHOD 50 JAVASCRIPT & JQUERY: THE MISSING MANUAL EXPLANATION Once they’ve completed their tasks of removing an item from an array, pop() and shift() return a value. In fact, they return the value that they just removed. So, for example, this code removes a value and stores that value in the variable removedItem: TUTORIAL: WRITING TO A WEB PAGE USING ARRAYS var p = [0,1,2,3]; var removedItem = p.shift(); The value of removedItem after this code runs is 0 and the array p now contains [1,2,3]. POWER USERS’ CLINIC Creating a Queue The methods used to add items to an array—push() and unshift()—and the methods used to remove items from an array—pop() and shift()—are often used together to provide a way of accessing items in the order they were created. A classic example is a music playlist. You create the list by adding songs to it; then, as you play each song, it’s removed from the list. The songs are played in the order they appear in the list, so the first song is played and then removed from the list. This arrangement is similar to a line at the movies. When you arrive at the movie theater, you take your place at the end of the line; when the movie’s about to begin, the doors open and the first person in line is the first to get in. the push() and shift() commands. For example, say you had an array named playlist. To add a new song to the end of the list, you’d use push(), like this: playlist.push('Yellow Submarine'); To get the song that’s supposed to play next, you get the first item in the list like this: nowPlaying = playlist.shift(); This code removes the first item from the array and stores it in a variable named nowPlaying. The FIFO concept is useful for creating and managing queues such as a playlist, a to-do list, or a slideshow. In programming circles, this concept is called FIFO for “First In, First Out.” You can simulate this arrangement using arrays and NOTE This chapter’s files include a web page that lets you interactively test the different array commands. It’s named array_methods.html and it’s in the testbed folder. Open the file in a web browser and click the various buttons on the web page to see how the array methods work. (By the way, all the cool interactivity of that page is thanks to JavaScript and jQuery.) Tutorial: Writing to a Web Page Using Arrays You’ll use arrays in many of the scripts in this book, but to get a quick taste of creating and using arrays, try this short tutorial. NOTE See the note on page 12 for information on how to download the tutorial files. Chapter 2: The Grammar of JavaScript 51 TUTORIAL: WRITING TO A WEB PAGE USING ARRAYS 1. In a text editor, open the file arrays.html in the chapter02 folder. You’ll start by simply creating an array containing four strings. As with the previous tutorial, this file already contains This code comprises a single JavaScript statement, but it’s broken over five lines. To create it, type the first line—var authors = [ 'Ernest Hemingway',—hit Return, then press the Space bar until you line up under the first ' (16 spaces), and then type 'Charlotte Bronte', hit Return and continue. NOTE Most HTML editors use a monospaced font like Courier or Courier New for your HTML and JavaScript code. In a monospaced font, each character is the same width as every other character, so it’s easy to line up columns (like all the author names in this example). If your text editor doesn’t use Courier or something similar, you may not be able to line up the names perfectly. As mentioned on page 46, when you create an array with lots of elements, you can make your code easier to read if you break it over several lines. You can tell it’s a single statement because there’s no semicolon until the end of line 5. This line of code creates an array named authors and stores the names of four authors (four string values) into the array. Next, you’ll access an element of the array. 3. Locate the second set of The first line starts a new paragraph with some text and an opening tag—just plain HTML. The next line prints the value stored in the first item of the authors array and prints the closing and tags to create a complete HTML paragraph. To access the first item in an array, you use a 0 as the index—authors[0]—instead of 1. At this point, it’s a good idea to save your file and preview it in a web browser. You should see “The first author is Ernest Hemingway” printed on the screen. 52 JAVASCRIPT & JQUERY: THE MISSING MANUAL If you don’t, you may have made a typo when you created the array in either step 2 or 3. TUTORIAL: WRITING TO A WEB PAGE USING ARRAYS NOTE Remember to use the error console in your browser (described on page 18) to help you locate the source of any JavaScript errors. 4. Return to your text editor and add these two lines of code below to your script: document.write('
The last author is '); document.write(authors[4] + '
'); This step is pretty much the same as the previous one, except that you’re printing a different array item. Save the page and preview it in a browser. You’ll see “undefined” in place of an author’s name (see Figure 2-6). Don’t worry; that’s intentional. Can you figure out why it’s not working? Remember that an array’s index values begin at 0, so the last item is actually the total number of items in the array minus 1. In this case, there are four strings stored in the authors array, so that last item would actually be accessed with authors[3]. NOTE If you try to read the value of an item using an index value that doesn’t exist, you’ll end up with the JavaScript “undefined” value. All that means is that there’s no value stored in that index position. Fortunately, there’s an easy technique for retrieving the last item in an array no matter how many items are stored in the array. 5. Return to your text editor and edit the code you just entered. Erase the 4 and add the bolded code in its place: document.write(‘The last author is ’); document.write(authors[authors.length-1] + ‘
’); As you’ll recall from “Adding Items to an Array” on page 48, an array’s length property stores the number of items in the array. So the total number of items in the authors array can be found with this code: authors.length. At this point in the script, that turns out to be 4. Knowing that the index value of the last item in an array is always 1 less than the total number of items in an array, you just subtract one from the total to get the index number of the last item: authors.length-1. You can provide that little equation as the index value when accessing the last item in an array: authors[authors.length-1]. You’ll finish up by adding one more item to the beginning of the array. Chapter 2: The Grammar of JavaScript 53 TUTORIAL: WRITING TO A WEB PAGE USING ARRAYS FIGURE 2-6 If you try to access an array element that doesn’t exist, then you’ll end up with the value “undefined.” 6. Add another line of code after the ones you added in step 5: authors.unshift('Stan Lee'); As you read on page 49, the unshift() method adds one or more items to the beginning of an array. After this line of code runs, the authors array will now be ['Stan Lee', 'Ernest Hemingway', 'Charlotte Bronte', 'Dante Alighieri','Emily Dickinson']. Finally, you’ll print out the newly added item on the page. 7. Add three more lines (bolded below) so that your final code looks like this: document.write('The first author is '); document.write(authors[0] + '
'); document.write('The last author is '); document.write(authors[authors.length-1] + '
'); authors.unshift('Stan Lee'); document.write('I almost forgot '); document.write(authors[0]); document.write('
'); Save the file and preview it in a web browser. You should see something like Figure 2-7. If you don’t, remember that the error console in your web browser can help you locate the error (page 18). 54 JAVASCRIPT & JQUERY: THE MISSING MANUAL A QUICK OBJECT LESSON FIGURE 2-7 OK, Stan Lee may not be your idea of a literary giant, but at least he’s helping you learn how arrays work. A Quick Object Lesson So far in this book, you’ve learned that you can write something to a web page with the document.write() command, and to determine how many items are in an array, you type the name of the array followed by a period and the word “length,” like so: days.length. You’re probably wondering what those periods are about. You’ve made it through three chapters without learning the particulars of this feature of JavaScript syntax, and it’s time to address them. You can conceptualize many of the elements of the JavaScript language, as well as elements of a web page, as objects. The real world, of course, is filled with objects too, such as a dog or a car. Most objects are made up of different parts: A dog has a tail, a head, and four legs; a car has doors, wheels, headlights, a horn; and so on. An object might also do something—a car can transport passengers, a dog can bark. In fact, even a part of an object can do something: For example, a tail can wag, and a horn can honk. Table 2-7 illustrates one way to show the relationships between objects, their parts, and actions. Chapter 2: The Grammar of JavaScript 55 A QUICK OBJECT LESSON TABLE 2-7 A simplified view of the world OBJECT PARTS dog ACTIONS bark tail car wag transport horn honk The world of JavaScript is also filled with objects: a browser window, a document, and a date are just a few examples. Like real-world objects, JavaScript objects are also made up of different parts. In programming-speak, the parts of an object are called properties. The actions an object can perform are called methods, which are functions (like the built-in alert() function) that are specific to an object (see Table 2-8). NOTE You can always tell a method from a property because when you use a method, the name ends in parentheses: write(), for example. Each object in JavaScript has its own set of properties and methods. For example, the array object has a property named length, and the document object has a method named write(). To access an object’s property or execute one of its methods, you use dot syntax—those periods! The dot (period) connects the object with its property or method. For example, document.write() means “run the write() method of the document object.” If the real world worked like that, you’d have a dog wag his tail like this: dog.tail.wag(). (Of course, in the real world, a doggy treat works a lot better.) TABLE 2-8 Some methods and properties of two JavaScript objects: the document object and an array OBJECT PROPERTY document title METHOD url write() ['Kate','Graham','Sam'] length push() pop() unshift() And just as you might own several dogs in the real world, your JavaScript programs can have multiple versions (called instances) of the same kind of object. For example, say you create two simple variables like this: var first_name = 'Jack'; var last_name = 'Hearts'; 56 JAVASCRIPT & JQUERY: THE MISSING MANUAL You’ve actually created two different string objects. Strings have their own set of properties and methods, which are different from the methods and properties of other objects, like dates (you’ll learn some of these properties and methods on page 568). When you create an object (also called creating an instance of that object), you can access all of the properties and methods for that object. A QUICK OBJECT LESSON NOTE You’ve already encountered another object—called the window object—which represents the browser window itself. It’s basically the container object for a web page and everything else on the page. For example, alert() and prompt() are both methods of the window object and can be written like this: window. alert() and window.prompt(). However, because the window object is always present in a web page, you can leave its name out, so alert('hello') and window.alert('hello') do the same thing. Whenever you create a new variable and store a value into it, you’re really creating a new instance of a particular type of object. So each of these lines of JavaScript create different types of JavaScript objects: var first_name = 'Bob'; // a string object var age = 32; // a number object var valid = false; // a Boolean object In fact, when you change the type of information stored in a variable, you change the type of object it is as well. For example, if you create a variable named data that stores an array, then store a number in the variable, you’ve changed that variable’s type from an array to a number object: var data = false; // a Boolean object data = 32; //changes to number object The concepts of objects, properties, methods, and dot syntax may seem a little weird at first glance. However, they are fundamental parts of how JavaScript works, and integral to using jQuery as well, so you’ll get used to them pretty quickly. TIP JavaScript includes a special keyword for determining the type of an object (string, number, Boolean, and so on). It’s called the typeof operator and is placed before a variable to determine the type of object inside that variable. For example: var data = 32; alert(typeof data); // "number" appears in alert window data = 'Roger roger'; alert(typeof data); // "string" appears in the alert window As you continue reading this book, keep these few facts in mind: • The world of JavaScript is populated with lots of different types of objects. • Each object has its own properties and methods. • You access an object’s property or activate an object’s method using dot syntax: document.write(), for example. Chapter 2: The Grammar of JavaScript 57 COMMENTS Comments When you’re in the midst of programming, you feel like you understand everything that’s going on in your program. Every line of code makes sense, and better yet, it works! But a month or two later, when your boss or a client asks you to make a change or add a new feature to that cool script you wrote, you might find yourself scratching your head the moment you look at your once-familiar JavaScript: What’s that variable for? Why’d I program it like that? What’s going on in this section of the program? It’s easy to forget how a program works and why you wrote your code the way you did. Fortunately, most programming languages provide a way for programmers to leave notes for themselves or other programmers who might look through their code. JavaScript lets you leave comments throughout your code. If you’ve used HTML or CSS comments, these should feel familiar. A comment is simply a line or more worth of notes: The JavaScript interpreter ignores them, but they can provide valuable information on how your program works. To create a single line comment, precede the comment with double forward slashes: // this is a comment You can also add a comment after a JavaScript statement: var price = 10; // set the initial cost of the widget The JavaScript interpreter ignores everything after the // until the end of the line. You can also add several lines worth of comments by beginning the comments with /* and ending them with */. (These are the same type of comments CSS uses.) The JavaScript interpreter ignores all of the text between these two sets of symbols. For example, say you want to give a description of how a program works at the beginning of your code. You can do that like this: /* JavaScript Slideshow: This program automates the display of images in a pop-up window. */ You don’t need to leave the /* and */ on their own lines, either. In fact, you can create a single line JavaScript comment with them: /* this is a single line comment */ In general, if you want to just write a short, one-line comment, use //. For several lines of comments, use the /* and */ combination. 58 JAVASCRIPT & JQUERY: THE MISSING MANUAL When to Use Comments Comments are an invaluable tool for a program that’s moderately long or complex and that you want to keep using (and perhaps changing) in the future. While the simple scripts you’ve learned so far are only a line or two of code, you’ll eventually be creating longer and much more complex programs. To make sure you can quickly figure out what’s going on in a script, it’s a good idea to add comments to help you understand the overall logic of the program and to explain any particularly confusing or complex bits. COMMENTS NOTE Adding lots of comments to a script makes the script larger (and slower to download). In general, the amount of comments you’ll add to a script won’t add significantly to the size of the file. But if you want to squeeze every unnecessary byte out of your files, page 585 shows you ways to make JavaScript files smaller and faster. Many programmers add a block of comments at the beginning of an external JavaScript file. These comments can explain what the script is supposed to do, identify the date the script was created, include a version number for frequently updated scripts, and provide copyright information. For example, at the beginning of the jQuery library’s JavaScript file, you’ll find this comment: /*! * jQuery JavaScript Library v1.11.0 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-23T21:02Z */ At the beginning of the script, you might also include instructions on how to use the script: variables that might need to be set, anything special you might need to do to your HTML to make the script work, and so on. You should also add a comment before a series of complex programming steps. For example, say you write a script that animates an image across a visitor’s browser window. One part of that script is determining the image’s current position in the browser window. This can take several lines of programming; it’s a good idea to place a comment before that section of the program, so when you look at the script later, you’ll know exactly what that part of the program does: // determine x and y positions of image in window Chapter 2: The Grammar of JavaScript 59 COMMENTS The basic rule of thumb is to add comments anywhere you’ll find them helpful later. If a line of code is painfully obvious, you probably don’t need a comment. For example, there’s no reason to add a comment for simple code like alert('hello'), because it’s pretty obvious what it does (opens an alert box with the word “hello” in it). Comments in This Book Comments are also very helpful when explaining JavaScript. In this book, comments frequently explain what a line of programming does or indicate the results of a particular statement. For example, you might see a comment like the following to show the results of an alert statement: var a = 'Bob'; var b = 'Smith'; alert(a + ' ' + b); // 'Bob Smith'; The third line ends with a comment that indicates what you should see when you preview this code in a web browser. If you want to test the code that you read in this book by adding it to a web page and viewing it in a web browser, you can leave out comments like these when typing the code into a web page. These types of comments are intended simply to help you understand what’s happening in the code as you read along with the book. Likewise, as you start to learn some of the more complex commands available in JavaScript, you’ll begin to manipulate the data in variables. You’ll often see comments in this book’s code to display what should be stored in the variable after the command is run. For example, the charAt() command lets you select a character at a specific point in a string. When you read about how to use that command in this book, you might see code like this: var x = "Now is the time for all good programmers."; alert(x.charAt(2)); // 'w' The comment // 'w' that appears at the end of the second line indicates what you should see in an alert dialog box if this code were actually run in a web browser. (And, yes, 'w' is correct. When counting the letters in a string, the first letter is counted as character 0, because strings are really arrays of characters. So charAt(2) retrieves the third character from the string. Sometimes programming just hurts your brain.) 60 JAVASCRIPT & JQUERY: THE MISSING MANUAL CHAPTER Adding Logic and Control to Your Programs 3 S o far you’ve learned about some of JavaScript’s basic building blocks. But simply creating a variable and storing a string or number in it doesn’t accomplish much. And building an array with a long list of items won’t be much help unless you have an easy way to work your way through the items in the array. In this chapter, you’ll learn how to make your programs react intelligently and work more efficiently by using conditional statements, loops, and functions. Making Programs React Intelligently Our lives are filled with choices: “What should I wear today?”, “What should I eat for lunch?”, “What should I do Friday night?”, and so on. Many choices you make depend on the situation. For example, say you decide you want to go to the movies on Friday night. You’ll probably ask yourself a bunch of questions like “Are there any good movies playing?”, “Is there a movie starting at the right time?”, “Do I have enough money to go to the movies (and buy a $17 bag of popcorn)?” Suppose there is a movie that’s playing at just the time you want to go. You then ask yourself a simple question: “Do I have enough money?” If the answer is yes, you’ll head out to the movie. If the answer is no, you won’t go. But on another Friday, you do have enough money, so you go to the movies. This scenario is just a simple example of how the circumstances around us affect the decisions we make. JavaScript has the same kind of decision-making feature called conditional statements. At its most basic, a conditional statement is a simple yes or no question. If the answer to the question is yes, your program does one thing; if the answer is no, it does something else. Conditional statements are one of the most useful programming 61 MAKING PROGRAMS REACT INTELLIGENTLY concepts: They let your programs react to different situations and behave intelligently. You’ll use them countless times in your programming. To get a clear picture of their usefulness, here are a few examples of how they can come in handy: • Form validation. When you want to make sure someone filled out all of the required fields in a form (“Name,” “Address,” “Email,” and so on), you’ll use conditional statements. For example, if the Name field is empty, don’t submit the form. • Drag and drop. If you add the ability to drag elements around your web page, you might want to check where the visitor drops the element on the page. For example, if he drops a picture onto an image of a trash can, you make the photo disappear from the page. • Evaluating input. Suppose you pop up a window to ask a visitor a question like, “Would you like to answer a few questions about how great this website is?” You’ll want your script to react differently depending on how the visitor answers the question. Figure 3-1 shows an example of an application that uses conditional statements. FIGURE 3-1 It takes a lot of work to have fun. A JavaScriptbased game like Solitaire (http://worldofsolitaire. com) demonstrates how a program has to react differently based on the conditions of the program. For example, when a player drags and drops a card, the program has to decide if the player dropped the card in a valid location or not, and then perform different actions in each case. 62 JAVASCRIPT & JQUERY: THE MISSING MANUAL Conditional Statement Basics Conditional statements are also called if/then statements, because they perform a task only if the answer to a question is true: “If I have enough money, then I’ll go to the movies.” The basic structure of an if/then conditional statement looks like this: MAKING PROGRAMS REACT INTELLIGENTLY if ( condition ) { // some action happens here } There are three parts to the statement: if indicates that the programming that follows is a conditional statement; the parentheses enclose the yes or no question, called the condition (more on that in a moment); and the curly braces ({ }) mark the beginning and end of the JavaScript code that should execute if the condition is true. NOTE In the code listed above, the // some action happens here is a JavaScript comment. It’s not code that actually runs; it’s just a note left amidst the code. In this case, the comment points out to you, the reader, what’s supposed to go in that part of the program. See page 58 for more on comments. In many cases, the condition is a comparison between two values. For example, say you create a game that the player wins when the score is over 100. In this program, you’ll need a variable to track the player’s score and, at some point, you need to check to see if that score is more than 100 points. In JavaScript, the code to check if the player won could look like this: if (score > 100) { alert('You won!'); } The important part is score > 100. That phrase is the condition, and it simply tests whether the value stored in the score variable is greater than 100. If it is, then a “You won!” dialog box appears; if the player’s score is less than or equal to 100, then the JavaScript interpreter skips the alert and moves onto the next part of the program. Figure 3-2 provides a visualization of this process. FIGURE 3-2 With a basic conditional statement, the code inside the braces only runs if the condition is true. If the condition is false, that code is skipped and the program continues. Chapter 3: Adding Logic and Control to Your Programs 63 MAKING PROGRAMS REACT INTELLIGENTLY In addition to > (greater than), there are several other conditional operators used to compare numbers (see Table 3-1). TIP Type two spaces (or press the Tab key once) before each line of JavaScript code contained within a pair of braces. The spaces (or tab) indent those lines and make it easier to see the beginning and ending brace, and to figure out what code belongs inside the conditional statement. Two spaces is a common technique, but if four spaces make your code easier for you to read, then use four spaces. The examples in this book indent code inside braces. TABLE 3-1 Use these comparison operators to test values as part of a conditional statement COMPARISON OPERATOR 64 WHAT IT MEANS == Equal to. Compares two values to see if they’re the same. Can be used to compare numbers or strings. != Not equal to. Compares two values to see if they’re not the same. Can be used to compare numbers or strings. === Strict equal to. Compares not only the values but also the type of the value. In other words, the two values must also share the same type— string, number, or Boolean—in order for the condition to be true. For example, while '2' == 2 is true, '2' === 2 is not true, because the first value is inside quote marks (a string) and the second is a number. Many programmers prefer this strict equality operator because it ensures you’re comparing like types of information. However, when retrieving a number value from a form (or a prompt() dialog box), you’ll get a string value like '2', and not an actual number. You should convert the string to a number before comparing using a comparison—see page 37 for more on converting strings to numbers. !== Strict not equal to. Like strict equal to compare values and type. For example, while '2' != 2 is false, '2' ! = = 2 is true, because although the values are the same, the types are not. > Greater than. Compares two numbers and checks if the number on the left side is greater than the number on the right. For example, 2 > 1 is true, since 2 is a bigger number than 1, but 2 > 3 is false, because 2 isn’t bigger than 3. < Less than. Compares two numbers and checks if the number on the left side is less than the number on the right. For example, 2 < 3 is true, because 2 is a smaller number than 3, but 2 < 1 is false, because 2 isn’t less than 1. >= Greater than or equal to. Compares two numbers and checks if the number on the left side is greater than or the same value as the number on the right. For example, 2 >= 2 is true, because 2 is the same as 2, but 2 >= 3 is false, because 2 isn’t a bigger number 3, nor is it equal to 3. <= Less than or equal to. Compares two numbers and checks if the number on the left side is less than or the same value as the number on the right. For example, 2 <= 2 is true, because 2 is the same as 2, but 2 <= 1 is false, because 2 isn’t a smaller number than 1, nor is 2 equal to 1. JAVASCRIPT & JQUERY: THE MISSING MANUAL You’ll frequently test to see if two values are equal or not. For example, say you create a JavaScript-based quiz, and one of the questions asks, “How many moons does Saturn have?” The person’s answer is stored in a variable named answer. You might then write a conditional statement like this: MAKING PROGRAMS REACT INTELLIGENTLY if (answer == 31) { alert('Correct. Saturn has 31 moons.'); } The double set of equals signs (==) isn’t a typo; it instructs the JavaScript interpreter to compare two values and decide whether they’re equal. As you learned in Chapter 2, in JavaScript, a single equals sign is the assignment operator that you use to store a value into a variable: var score = 0; //stores 0 into the variable score Because the JavaScript interpreter already assigns a special meaning to a single equals sign, you need to use two equals signs whenever you want to compare two values to determine if they’re equal or not. You can also use the == (called the equality operator) to check to see if two strings are the same. For example, say you let the user type a color into a form, and if he types red, then you change the background color of the page to red. You could use the conditional operator for that: if (enteredColor == 'red') { document.body.style.backgroundColor='red'; } NOTE In the code above, don’t worry right now about how the page color is changed. You’ll learn how to dynamically control CSS properties using JavaScript on page 134. You can also test to see if two values aren’t the same using the inequality operator: if (answer != 31) { alert("Wrong! That's not how many moons Saturn has."); } The exclamation mark translates to “not”, so != means “not equal to.” In this example, if the value stored in answer is not 31, then the poor test taker would see the insulting alert message. The code that runs if the condition is true isn’t limited to just a single line of code as in the previous examples. You can have as many lines of JavaScript between the opening and closing curly braces as you’d like. For example, as part of the JavaScript quiz example, you might keep a running tally of how many correct answers the test taker gets. Chapter 3: Adding Logic and Control to Your Programs 65 MAKING PROGRAMS REACT INTELLIGENTLY So, when the Saturn question is answered correctly, you also want to add 1 to the test taker’s total. You would do that as part of the conditional statement: if (answer == 31) { alert('Correct. Saturn has 31 moons.'); numCorrect += 1; } NOTE As described on page 39, the line of code above—numCorrect += 1—simply adds 1 to the value currently in the variable numCorrect. And you could add additional lines of JavaScript code between the braces as well— any code that should run if the condition is true. POWER USERS’ CLINIC The Return of the Boolean On page 29, you learned about the Boolean values—true and false. Booleans may not seem very useful at first, but they’re essential when you start using conditional statements. In fact, because a condition is really just a yes or no question, the answer to that question is a Boolean value. For example, check out the following code: var x = 4; if ( x == 4 ) { //do something } The first line of code stores the number 4 into the variable x. The condition on the next line is a simple question: Is the value stored in x equal to 4? In this case, it is, so the JavaScript between the curly braces runs. But here’s what really happens in between the parentheses: The JavaScript interpreter converts the condition into a Boolean value. (In programming-speak, the interpreter evaluates the condition.) If the condition evaluates to true (meaning the answer to the question is yes), then the code between the braces runs. However, if the condition evaluates to false, then the code in the braces is skipped. One common use of Booleans is to create what’s called a flag—a variable that marks whether something is true. For example, when validating a form full of visitor-submitted information, you might start by creating a valid variable with a Boolean value of true—this means you’re assuming, at first, that she filled out the form correctly. Then, you’d run through each form field, and if any field is missing information or has the wrong type of information, you’d change the value in valid to false. After checking all of the form fields, you’d test what’s stored in valid, and if it’s still true, you submit the form. If it’s not true (meaning one or more form fields were left blank), you’d display some error messages and prevent the form from submitting: var valid = true; // lot of other programming gunk happens in here // if a field has a problem then you set valid to false if (valid) { //submit form } else { //print lots of error messages } Adding a Backup Plan But what if the condition is false? The basic conditional statement in the previous section doesn’t have a backup plan for a condition that turns out to be false. In the 66 JAVASCRIPT & JQUERY: THE MISSING MANUAL real world, if you’re deciding what to do Friday night and you don’t have enough money for the movies, you’d want to do something else. An if statement has its own kind of backup plan, called an else clause. For example, say as part of the JavaScript testing script, you want to notify the test taker if he gets the answer right, or if he gets it wrong. Here’s how you can do that: MAKING PROGRAMS REACT INTELLIGENTLY if (answer == 31) { alert('Correct. Saturn has 31 moons.'); numCorrect = numCorrect + 1; } else { alert("Wrong! That's not how many moons Saturn has."); } This code sets up an either/or situation; only one of the two messages will appear (Figure 3-3). If the number 31 is stored in the variable answer, then the “correct” alert appears; otherwise, the “wrong” alert appears. To create an else clause, just add else after the closing brace for the conditional statement followed by another pair of braces. You add the code that should execute if the condition turns out to be false in between the braces. Again, you can have as many lines of code as you’d like as part of the else clause. FIGURE 3-3 When using an if else condition, you include two sets of code, but only one set will ever run. If the condition is true, then the code in the braces immediately following the condition runs (left); however, if the condition is false, then the code in the braces following the else runs (right). Testing More Than One Condition Sometimes you’ll want to test several conditions and have several possible outcomes: Think of it like a game show where the host says, “Would you like the prize behind door #1, door #2, or door #3?” You can only pick one. In your day-to-day activities, you also are often faced with multiple choices like this one. For example, return to the “What should I do Friday night?” question. You could expand your entertainment options based on how much money you have and are willing to spend. For example, you could start off by saying, “If I have $50 or more, Chapter 3: Adding Logic and Control to Your Programs 67 MAKING PROGRAMS REACT INTELLIGENTLY I’ll go out to a nice dinner and a movie (and have some popcorn too).” If you don’t have $50, you might try another test: “If I have $35 or more, I’ll go to a nice dinner.” If you don’t have $35, then you’d say, “If I have $12 or more, I’ll go to the movies.” And finally, if you don’t have $12, you might say, “Then I’ll just stay at home and watch TV.” What a Friday night! JavaScript lets you perform the same kind of cascading logic using else if statements. It works like this: You start with an if statement, which is option number 1; you then add one or more else if statements to provide additional questions that can trigger additional options; and finally, you use the else clause as the fallback position. Here’s the basic structure in JavaScript: if (condition) { // door #1 } else if (condition2) { // door #2 } else { // door #3 } This structure is all you need to create a JavaScript “Friday night planner” program. It asks visitors how much money they have, and then determines what they should do on Friday (sound familiar?). You can use the prompt() command that you learned about on page 42 to collect the visitor’s response and a series of if/else if statements to determine what he should do: var fridayCash = prompt('How much money can you spend?', ''); if (fridayCash >= 50) { alert('You should go out to dinner and a movie.'); } else if (fridayCash >= 35) { alert('You should go out to a fine meal.'); } else if (fridayCash >= 12) { alert('You should go see a movie.'); } else { alert('Looks like you will be watching TV.'); } Here’s how this program breaks down step by step: The first line opens a prompt dialog box asking the visitor how much he can spend. Whatever the visitor types is stored in a variable named fridayCash. The next line is a test: Is the value the visitor typed 50 or more? If the answer is yes, then an alert appears, telling him to go get a meal and see a movie. At this point, the entire conditional statement is done. The JavaScript interpreter skips the next else if statement, the following else if statement, and the final else clause. With a conditional statement, only one of the outcomes can happen, so once the JavaScript interpreter encounters a condition that evaluates to true, it runs the JavaScript code between the braces for that condition and skips everything else within the conditional statement (Figure 3-4). 68 JAVASCRIPT & JQUERY: THE MISSING MANUAL NOTE The JavaScript interpreter is actually looking for a “truthy” value when it evaluates a conditional statement. In fact, JavaScript has a concept of “truthy” and “falsy” values that cover more than just the value true and false. Sound confusing? It is. You’ll learn more about this advanced concept later in the book. MAKING PROGRAMS REACT INTELLIGENTLY FIGURE 3-4 With a basic conditional statement, the code inside the braces only runs if the condition is true. If the condition is false, that code is skipped and the program continues. You’ll find a working example of this code in the chapter03 tutorial folder in the file named friday_night. html. Suppose the visitor typed 25. The first condition, in this case, wouldn’t be true because 25 is a smaller number than 50. So the JavaScript interpreter skips the code within the braces for that first condition and continues to the else if statement: “Is 25 greater than or equal to 35?” Because the answer is no, it skips the code associated with that condition and encounters the next else if. At this point, the condition asks if 25 is greater than or equal to 12; the answer is yes, so an alert box with the message, “You should go see a movie” appears and the program ends, skipping the final else clause. Chapter 3: Adding Logic and Control to Your Programs 69 MAKING PROGRAMS REACT INTELLIGENTLY The order in which you place your conditional statements can affect how the program runs. For example, say you switched the order of the conditional statements in the above example: var fridayCash = prompt('How much money can you spend?', ''); if (fridayCash >= 12) { alert('You should go see a movie.'); } else if (fridayCash >= 35) { alert('You should go out to a fine meal.'); } else if (fridayCash >= 50) { alert('You should go out to dinner and a movie.'); } else { alert('Looks like you will be watching TV.'); } No matter how much money you have you’ll never get the “You should go out to a fine meal” or “You should go out to dinner and a movie” message. If you have $100, then the above program would first ask “Is 100 >= 12?” Of course, the answer to that is Yes, so you see the message, “You should go see a movie,” and the other conditions are simply skipped, even though you have enough money for the two other options. You’ll encounter this problem when comparing numeric values using the < or > operators. Because lots of different numbers can be larger or smaller than another number, there are multiple possible “yes” answers. For testing if a variable is equal to some value, there’s only one possible answer, so you can put those types of comparison in any order in an if / else if / then series of statements. TIP There’s another way to create a series of conditional statements that all test the same variable, as in the fridayCash example. Switch statements do the same thing, and you’ll learn about them on page 579. More Complex Conditions When you’re dealing with many different variables, you’ll often need even more complex conditional statements. For example, when validating a required email address field in a form, you’ll want to make sure both that the field isn’t empty and that the field contains an email address (and not just random typed letters). Fortunately, JavaScript lets you do these kinds of checks as well. MAKING SURE MORE THAN ONE CONDITION IS TRUE You’ll often need to make decisions based on a combination of factors. For example, you may only want to go to a movie if you have enough money and there’s a movie you want to see. In this case, you’ll go only if two conditions are true; if either one is false, then you won’t go to the movie. In JavaScript, you can combine conditions using what’s called the logical AND operator, which is represented by two ampersands (&&). You can use it between the two conditions within a single conditional statement. For example, if you want to check if a number is between 1 and 10, you can do this: 70 JAVASCRIPT & JQUERY: THE MISSING MANUAL if (a > 1 && a < 10) { //the value in a is between 1 and 10 alert("The value " + a + " is between 1 and 10"); } MAKING PROGRAMS REACT INTELLIGENTLY In this example, there are two conditions: a > 1, is the same as “Is the value in a greater than 1?”; a < 10 asks if the value stored in the variable a is less than 10. The JavaScript contained between the braces will run only if both conditions are true. So if the variable a has the number 0 stored in it, the first condition (a < 10) is true (0 is less than 10), but the second condition is false (0 is not greater than 1). You’re not limited to just two conditions. You can connect as many conditions as you need with the && operator: if (b>0 && a>0 && c>0) { // all three variables are greater than 0 } This code checks three variables to make sure all three have a value greater than 0. If just one has a value of 0 or less, then the code between the braces won’t run. MAKING SURE AT LEAST ONE CONDITION IS TRUE Other times you’ll want to check a series of conditions, but you only need one to be true. For example, say you’ve added a keyboard control for visitors to jump from picture to picture in a photo gallery. When the visitor presses the N key, the next photo appears. In this case, you want her to go to the next picture when she types either n (lowercase), or if she has the Caps Lock key pressed, N (uppercase). You’re looking for a kind of either/or logic: Either this key or that key was pressed. The logical OR operator, represented by two pipe characters (||), comes in handy: if (key == 'n' || key == 'N') { //move to the next photo } NOTE To type a pipe character, press Shift-\. The key that types both backslashes and pipe characters is usually located just above the Return key. With the OR operator, only one condition needs to be true for the JavaScript that follows between the braces to run. As with the AND operator, you can compare more than two conditions. For example, say you’ve created a JavaScript racing game. The player has a limited amount of time, a limited amount of gas, and a limited number of cars (each time he crashes, he loses one car). To make the game more challenging, you want it to come to an end when any of these three things runs out: if (gas <= 0 || time <= 0 || cars <= 0) { //game is over } Chapter 3: Adding Logic and Control to Your Programs 71 MAKING PROGRAMS REACT INTELLIGENTLY When testing multiple conditions, it’s sometimes difficult to figure out the logic of the conditional statement. Some programmers group each condition in a set of parentheses to make the logic easier to grasp: if ((key == 'n') || (key == 'N')) { //move to the next photo } To read this code, simply treat each grouping as a separate test; the results of the operation between parentheses will always turn out to be either true or false. NEGATING A CONDITION If you’re a Superman fan, you probably know about Bizarro, an anti-hero who lived on a cubical planet named Htrae (Earth spelled backwards), had a uniform with a backwards S, and was generally the opposite of Superman in every way. When Bizarro said “Yes,” he really meant “No,” and when he said “No,” he really meant “Yes.” JavaScript programming has an equivalent type of character called the NOT operator, which is represented by an exclamation mark (!). You’ve already seen the NOT operator used along with the equals sign to indicate “not equal to”: !=. But the NOT operator can be used by itself to completely reverse the results of a conditional statement; in other words, it can make false mean true, and true mean false. You use the NOT operator when you want to run some code based on a negative condition. For example, say you’ve created a variable named valid that contains a Boolean value of either true or false (see the box on page 66). You use this variable to track whether a visitor correctly filled out a form. When the visitor tries to submit the form, your JavaScript checks each form field to make sure it passes the requirements you set up (for example, the field can’t be empty and it has to have an email address in it). If there’s a problem, like the field is empty, you could then set valid to false (valid = false). Now if you want to do something like print out an error and prevent the form from being submitted, you can write a conditional statement like this: if (! valid) { //print errors and don't submit form } The condition ! valid can be translated as “if not valid,” which means if valid is false, then the condition is true. To figure out the results of a condition that uses the NOT operator, just evaluate the condition without the NOT operator, then reverse it. In other words, if the condition results to true, the ! operator changes it to false, so the conditional statement doesn’t run. As you can see, the NOT operator is very simple to understand (translated from Bizarro-speak: It’s very confusing, but if you use it long enough, you’ll get used to it). 72 JAVASCRIPT & JQUERY: THE MISSING MANUAL Nesting Conditional Statements In large part, computer programming entails making decisions based on information the visitor has supplied or on current conditions inside a program. The more decisions a program makes, the more possible outcomes and the “smarter” the program seems. In fact, you might find you need to make further decisions after you’ve gone through one conditional statement. MAKING PROGRAMS REACT INTELLIGENTLY Suppose, in the “What to do on Friday night?” example, you want to expand the program to include every night of the week. In that case, you need to first determine what day of the week it is, and then figure out what to do on that day. So you might have a conditional statement asking if it’s Friday, and if it is, you’d have another series of conditional statements to determine what to do on that day: if (dayOfWeek == 'Friday') { var fridayCash = prompt('How much money can you spend?', ''); if (fridayCash >= 50) { alert('You should go out to dinner and a movie.'); } else if (fridayCash >= 35) { alert('You should go out to a fine meal.'); } else if (fridayCash >= 12) { alert('You should go see a movie.'); } else { alert('Looks like you will be watching TV.'); } } In this example, the first condition asks if the value stored in the variable dayOfWeek is the string 'Friday'. If the answer is yes, then a prompt dialog box appears, gets some information from the visitor, and another conditional statement is run. In other words, the first condition, (dayOfWeek == 'Friday'), is the doorway to another series of conditional statements. However, if dayOfWeek isn’t 'Friday', then the condition is false and the nested conditional statements are skipped. Tips for Writing Conditional Statements The example of a nested conditional statement in the last section may look a little scary. There are lots of (), {}, elses, and ifs. And if you happen to mistype one of the crucial pieces of a conditional statement, your script won’t work. There are a few things you can do as you type your JavaScript that can make it easier to work with conditional statements. • Type both of the curly braces before you type the code inside them. One of the most common mistakes programmers make is forgetting to add a final brace to a conditional statement. To avoid this mistake, type the condition and the braces first, then type the JavaScript code that executes when the condition is true. For example, start a conditional like this: if (dayOfWeek=='Friday') { } Chapter 3: Adding Logic and Control to Your Programs 73 TUTORIAL: USING CONDITIONAL STATEMENTS In other words, type the if clause and the first brace, hit Return twice, and then type the last brace. Now that the basic syntax is correct, you can click in the empty line between the braces and add JavaScript. • Indent code within braces. You can better visualize the structure of a conditional statement if you indent all of the JavaScript between a pair of braces: if (a < 10 && a > 1) { alert("The value " + a + " is between 1 and 10"); } By using several spaces (or pressing the Tab key) to indent lines within braces, it’s easier to identify which code will run as part of the conditional statement. If you have nested conditional statements, indent each nested statement: if (a < 10 && a > 1) { //first level indenting for first conditional alert("The value " + a + " is between 1 and 10"); if (a==5) { //second level indenting for 2nd conditional alert(a + " is half of ten."); } } • Use == for comparing equals. When checking whether two values are equal, don’t forget to use the equality operator, like this: if (name == 'Bob') { A common mistake is to use a single equals sign, like this: if (name = 'Bob') { A single equals sign stores a value into a variable, so in this case, the string 'Bob' would be stored in the variable name. Frustratingly, the JavaScript interpreter treats this step as true, so the code following the condition will always run. Tutorial: Using Conditional Statements Conditional statements will become part of your day-to-day JavaScript toolkit. In this tutorial, you’ll try out conditional statements to control how a script runs. NOTE See the note on page 12 for information on how to download the tutorial files. 1. In a text editor, open the file conditional.html in the chapter03 folder. You’ll start by simply prompting the visitor for a number. This file already contains This line of code opens a JavaScript prompt dialog box, asks a question, and stores whatever the visitor typed into the luckyNumber variable (remember: the = sign stores a value in a variable). Next, you’ll add a conditional statement to check what the visitor typed into the prompt dialog box. 3. Locate the second set of Don’t forget the double equals signs (==), which compare two values. Here’s the beginning of the conditional statement; it simply checks to see if the visitor typed 7. 4. Press Return twice and type the closing brace, so the code looks like this: The closing brace ends the conditional statement. Any JavaScript you add between the two braces will run only if the condition is true. NOTE As mentioned on page 73, it’s a good idea to add the closing brace before writing the code that runs as part of the conditional statement. 5. Click into the empty line above the closing brace. Hit the space bar twice and type: document.write("Hey, 7 is my lucky number too!
"); The two spaces before the code indent the line so you can easily see that this code is part of the conditional statement. The actual JavaScript here should feel familiar by now—it simply writes a message to the page. 6. Save the file and preview it in a web browser. Type 7 when the prompt dialog box appears. You should see the message “Hey, 7 is my lucky number too!” below the headline when the page loads. If you don’t, go over your code and make sure you typed it correctly (see page 18 for tips on dealing with a broken script). Reload Chapter 3: Adding Logic and Control to Your Programs 75 TUTORIAL: USING CONDITIONAL STATEMENTS the page, but this time type a different number. This time, nothing appears underneath the headline. You’ll add an else clause to print another message. 7. Return to your text editor, and add the bolded text to your page: The else clause provides a backup message, so if the visitor doesn’t type 7, she’ll see a different message that includes her lucky number. To round out this exercise, you’ll add an else if statement to test more values and provide another message. FREQUENTLY ASKED QUESTION Seeing Double 76 JAVASCRIPT & JQUERY: THE MISSING MANUAL At this point, the script first checks to see if 7 is stored in the variable luckyNumber; if luckyNumber holds a value other than 7, then the else if kicks in. This conditional statement is made up of two conditions, luckyNumber == 13 and luckyNumber == 24. The ||, called the logical OR operator, makes the entire conditional statement turn out to be true if either of the conditions are true. So if the visitor types in 13 or 24, a “That’s an unlucky number” message is printed to the page. NOTE TUTORIAL: USING CONDITIONAL STATEMENTS You add the logical OR operator by typing Shift-\ twice to get ||. Preview the page in a web browser, and type 13 when the prompt dialog box appears. Press the browser’s reload button, and try different numbers as well as letters or other characters. You’ll notice that if you type a word or other nonnumber character, the final else clause kicks in, printing a message like, “The number asdfg is lucky for you!” That doesn’t make a lot of sense, so you’ll pop up another prompt dialog box if your visitor enters a non-number the first time. 9. Return to your text editor, and locate the first set of This line of code runs the value of luckyNumber through a function named parseInt(). This JavaScript command takes a value and tries to convert it to an integer, which is a whole number like -20, 0, 1, 5, or 100. You can learn about this command on page 562, but for now just realize that if the visitor types in text like “ha ha,” the parseInt() command won’t be able to convert that to a number; instead, the command will provide a special JavaScript value, NaN, which stands for “not a number.” You can use that information to pop up another prompt dialog box if a number isn’t entered the first time. 10. Add the bolded code to your script: Here again, a conditional statement comes in handy. The condition isNaN(luckyNumber) uses another JavaScript command that checks to see if something is a number. Specifically, it checks to see if the value in luckyNumber is not a number. If the value isn’t a number (for example, the visitor types asklsdkl), a second prompt appears and asks the question again. If the visitor did type a number, the second prompt is skipped. Chapter 3: Adding Logic and Control to Your Programs 77 HANDLING REPETITIVE TASKS WITH LOOPS Save the page and preview it in a web browser again. This time, type a word and click OK when the prompt dialog box appears. You should then see a second prompt. Type a number this time. Of course, this script assumes the visitor made an honest mistake by typing a word the first time, but won’t make the same mistake twice. Unfortunately, if the visitor types a word in the second prompt, you end up with the same problem—you’ll learn how to fix that in the next section. NOTE You’ll find a completed version of this tutorial in the chapter03 tutorial folder: complete_conditional. html. Handling Repetitive Tasks with Loops Sometimes a script needs to repeat the same series of steps over and over again. For example, say you have a web form with 30 text fields. When the user submits the form, you want to make sure that none of the fields are empty. In other words, you need to perform the same set of actions—check to see if a form field is empty—30 times. Computers are good at performing repetitive tasks, so it makes sense that JavaScript includes the tools to quickly do the same thing repeatedly. In programming-speak, performing the same task over and over is called a loop, and because loops are so common in programming, JavaScript offers several different types. All do the same thing, just in slightly different ways. While Loops A while loop repeats a chunk of code as long as a particular condition is true; in other words, while the condition is true. The basic structure of a while loop is this: while (condition) { // javascript to repeat } The first line introduces the while statement. As with a conditional statement, you place a condition between the set of parentheses that follow the keyword while. The condition is any test you’d use in a conditional statement, such as x > 10 or answer == 'yes'. And just like a conditional statement, the JavaScript interpreter runs all of the code that appears between the opening and closing braces if the condition is true. However, unlike a conditional statement, when the JavaScript interpreter reaches the closing brace of a while statement, instead of continuing to the next line of the program, it jumps back to the top of the while statement and tests the condition a second time. If the condition is again true, the interpreter runs the JavaScript between the braces a second time. This process continues until the condition is no longer true; then the program continues to the next statement following the loop (Figure 3-5). 78 JAVASCRIPT & JQUERY: THE MISSING MANUAL HANDLING REPETITIVE TASKS WITH LOOPS FIGURE 3-5 A while loop runs the JavaScript code between curly braces as long as the test condition (x < 10 in this case) is true. Say you want to print the numbers 1 to 5 on a page. One possible way to do that is like this: document.write('Number document.write('Number document.write('Number document.write('Number document.write('Number 1 2 3 4 5
');
');
');
');
'); Notice that each line of code is nearly identical—only the number changes from line to line. In this situation, a loop provides a more efficient way to achieve the same goal: var num = 1; while (num <= 5) { document.write('Number ' + num + '
'); num += 1; } The first line of code—var num = 1;—isn’t part of the while loop: Instead, it sets up a variable to hold the number to be printed to the page. The second line is the start of the loop. It sets up the test condition. As long as the number stored in the variable num is less than or equal to 5, the code between the braces runs. When the test condition is encountered for the first time, the value of num is 1, so the test is true (1 is less than 5), and the document.write() command executes, writing “Number 1
” to the page (the
is just an HTML line break to make sure each line prints onto a separate line on the web page). NOTE A more compact way to write num += 1 (which just adds one to the current number stored in the variable num) is like this: num++ This shorthand method also adds one to the variable num (see Table 2-3 on page 39 for more information.) Chapter 3: Adding Logic and Control to Your Programs 79 HANDLING REPETITIVE TASKS WITH LOOPS The last line of the loop—num += 1—is very important. Not only does it increase the value of num by 1 so the next number (2, for example) will print, but it also makes it possible for the test condition to eventually turn out to be false (if the += operator looks weird, turn back to page 39 for an explanation of how it works). Because the JavaScript code within a while statement repeats as long as the condition is true, you must change one of the elements of the condition so the condition eventually becomes false in order to stop the loop and move onto the next part of the script. If the test condition never turns out to be false, you end up with what’s called an infinite loop—a program that never ends. Notice what would happen if you left that line out of the loop: var num = 1; while (num <= 5) { // this is an endless loop document.write('Number ' + num + '
'); } The first time through this loop, the test would ask: Is 1 less than or equal to 5? The answer is yes, so document.write() runs. At the end of the loop (the last brace), the JavaScript interpreter goes back to the beginning of the loop and tests the condition again. At this point, num is still 1, so the condition is true again and the document. write() executes. Again, the JavaScript interpreter returns to the beginning of the loop and tests the condition a third time. You can see where this goes: an endless number of lines that say “Number 1.” This simple example also shows some of the flexibility offered by loops. Say, for example, you wanted to write the numbers 1–100, instead of just 1–5. Instead of adding lots of additional lines of document.write() commands, you just alter the test condition like this: var num = 1; while (num <= 100) { document.write('Number ' + num + '
'); num = num + 1; } Now the loop will execute 100 times, writing 100 lines to the web page. Loops and Arrays You’ll find loops come in handy when dealing with a common JavaScript element—an array. As you recall from page 44, an array is a collection of data. You can think of an array as a kind of shopping list. When you go shopping, you actually perform a kind of loop: You walk around the store looking for an item on your list and, when you find it, you put it into your cart; then you look for the next item on your list, put it into the cart, and so on, until you’ve gone through the entire list. Then you’re done (this is the same as exiting the loop) and you can go to the checkout counter (in other words, move to the next step of your “program”). 80 JAVASCRIPT & JQUERY: THE MISSING MANUAL You can use loops in JavaScript to go through items in an array and perform a task on each item. For example, say you’re building a program that generates a calendar. The calendar is completely generated using JavaScript, and you want to print the name of each day of the week on the calendar. You might start by storing the names of the days into an array like this: HANDLING REPETITIVE TASKS WITH LOOPS var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', ↵ 'Friday', 'Saturday', 'Sunday']; NOTE The ↵ symbol that appears in the code above indicates that this line of JavaScript code belongs on a single line. The width of this book’s pages sometimes prevents a single line of code from fitting on a single printed line, the ↵ symbol is used to indicate code that should appear together on a single line. If you were going to type this code into a text editor, you’d type it as one long line (and leave out the ↵). You can then loop through each item in the array and print it to the page. Remember that you access one item in an array using the item’s index value. For example, the first item in the days array above (Monday) is retrieved with days[0]. The second item is days[1], and so on. Here’s how you can use a while loop to print each item in this array: var counter = 0; while (counter < days.length) { document.write(days[counter] + ', '); counter++; } The first line—var counter = 0—sets up (or initializes) a counter variable that’s used both as part of the test condition, and as the index for accessing array items. The condition—counter < days.length—just asks if the current value stored in the counter variable is less than the number of items in the array (remember, as described on page 48, the number of items in an array is stored in the array’s length property). In this case, the condition checks if the counter is less than 7 (the number of days in the week). If counter is less than 7, then the loop begins: The day of the week is written to the page (followed by a comma and a space), and the counter is incremented by 1 (counter++ is the same as counter += 1, or counter = counter + 1 [see page 39]). After the loop runs, it tries the test again; the loop continues to run until the test turns out to be false. This process is diagrammed in Figure 3-6. Chapter 3: Adding Logic and Control to Your Programs 81 HANDLING REPETITIVE TASKS WITH LOOPS FIGURE 3-6 For this loop, the condition is tested 8 times. The last test asks if 7 is less than 7. It isn’t, so the while statement is completed, and the JavaScript interpreter skips the loop and continues with the next part of the script. The final result of this script will be “Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday,.” Notice that there’s a comma after Sunday as well. To avoid this extra comma, you could use the array object’s join() method; this advanced technique is described on page 582 For Loops JavaScript offers another type of loop, called a for loop, that’s a little more compact (and a little more confusing). For loops are usually used for repeating a series of steps a certain number of times, so they often involve some kind of counter variable, a conditional test, and a way of changing the counter variable. In many cases, a for loop can achieve the same thing as a while loop, with fewer lines of code. For example, here’s the while loop shown on page 79: var num = 1; while (num <= 100) { document.write('Number ' + num + '
'); num += 1; } You can achieve the same effect using a for loop with only three lines of code: for (var num = 1; num <= 100; num++) { document.write('Number ' + num + '
'); } At first, for loops might look a little confusing, but once you figure out the different parts of the for statement, they aren’t hard. Each for loop begins with the keyword for, followed by a set of parentheses containing three parts, and a pair of curly braces. As with while loops, the stuff inside curly braces (document.write('Number' + num + '
'); in this example) is the JavaScript code that executes as part of the loop. 82 JAVASCRIPT & JQUERY: THE MISSING MANUAL Table 3-2 explains the three parts inside the parentheses, but in a nutshell, the parts are: initialize a counter, test a condition, and change the counter. The first part (var num=1;) initializes a counter variable. This step only happens once at the very beginning of the statement. The second part is the condition, which is tested to see if the loop is run; the third part is an action that happens at the end of each loop—it usually changes the value of the counter, so the test condition eventually turns out to be false and the loop ends. HANDLING REPETITIVE TASKS WITH LOOPS TABLE 3-2 Understanding the parts of a for loop PARTS OF LOOP WHAT IT MEANS WHEN IT’S APPLIED for Introduces the for loop. var num = 1; Set variable num to 1. Only once; at the very beginning of the statement. num <= 100; Is num less than or equal to 100? If yes, then loop again. If not, then skip loop and continue script. Before each time through the loop. num++ Add 1 to variable num. Same as num=num + 1 and num+=1. At end of each time through loop. Because for loops provide an easy way to repeat a series of steps a set number of times, they work really well for working through the elements of an array. The while loop in Figure 3-5, which writes each item in an array to the page, can be rewritten using a for loop, like this: var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', ↵ 'Friday', 'Saturday', 'Sunday']; for (var i=0; i= 0; j--) { document.write(example[j] + '
'); } Chapter 3: Adding Logic and Control to Your Programs 83 HANDLING REPETITIVE TASKS WITH LOOPS In this example, the counter variable j starts with the total number of items in the array minus 1 (4-1=3). (Why minus 1? Because accessing an item in an array is always one less than the item’s place in the array: the first item’s index is 0, the second’s is 1, and the last item is the length of the array minus 1. In other words, to access the last item in this array, you’d type example[3]). Each time through the loop, you test to see if the value in j is greater than or equal to 0; if it is, the code between the curly braces runs. Then, 1 is subtracted from j (j--), and the test is run again. So this loop moves backwards from the end of the array (the item with an index of 3) to the beginning of the array (the item with an index of 0). Do/While Loops There’s another, less common type of loop, known as a do/while loop. This type of loop works nearly identically to a while loop. Its basic structure looks like this: do { // javascript to repeat } while (condition) ; In this type of loop, the conditional test happens at the end, after the loop has run. As a result, the JavaScript code within the curly braces always run at least once. Even if the condition isn’t ever true, the test isn’t performed until after the code runs once. There aren’t too many cases where this comes in handy, but it’s very useful when you want to prompt the user for input. The tutorial you did earlier in this chapter (page 74) is a good example. That script asks visitors to type in a number. It includes a bit of a fail-safe system, so if they don’t type a number, the script asks them one more time to type a number. Unfortunately, if someone’s really stubborn and types something other than a number the second time, a nonsensical message is printed to the page. However, with a do/while loop, you can continually prompt the visitor for a number until she types one in. To see how this works, you’ll edit the page you completed on page 77: 1. In a text editor, open the conditional.html page you completed on page 77. (If you didn’t complete that tutorial, you can just open the file complete_conditional.html.) You’ll replace the code near the top of the page with a do/while loop. 2. Locate the code between the Save the page and preview it in a web browser (Figure 3-7). The current date is printed to the page. If you wanted to print the date at the bottom of the web page as well, all you’d need to do is call the function a second time. FIGURE 3-7 The final result of your first function. The date you see on your page will be different than the one pictured here. That’s part of the dynamic nature of functions—they run when you call them, so each day the printToday function is called a different date appears. Giving Information to Your Functions Functions are even more useful when they receive information. Think back to your assistant—the fellow who fetches you slices of pizza. The original “function” described on page 85 was simply directions to the pizza parlor and instructions to buy a slice and return to the office. When you wanted some pizza, you “called” the function by 88 JAVASCRIPT & JQUERY: THE MISSING MANUAL telling your assistant “Get me a slice!” Of course, depending on how you’re feeling, you might want a slice of pepperoni, cheese, or olive pizza. To make your instructions more flexible, you can tell your assistant what type of slice you’d like. Each time you request some pizza, you can specify a different type. FUNCTIONS: TURN USEFUL CODE INTO REUSABLE COMMANDS JavaScript functions can also accept information, called parameters, which the function uses to carry out its actions. For example, if you want to create a function that calculates the total cost of a person’s shopping cart, then the function needs to know how much each item costs, and how many of each item was ordered. To start, when you create the function, place the name of a new variable inside the parentheses—this is the parameter. The basic structure looks like this: function functionName(parameter) { // the JavaScript you want to run } The parameter is just a variable, so you supply any valid variable name (see page 30 for tips on naming variables). For example, say you want to save a few keystrokes each time you print something to a web page. You create a simple function that lets you replace the web browser’s document.write() function with a shorter name: function print(message) { document.write(message); } The name of this function is print and it has one parameter, named message. When this function is called, it receives some information (the message to be printed) and then it uses the document.write() function to write the message to the page. Of course, a function doesn’t do anything until it’s called, so somewhere else on your web page, you can call the function like this: print('Hello world.'); When this code is run, the print function is called and some text—the string 'Hello world.'—is sent to the function, which then prints “Hello world.” to the page. Technically, the process of sending information to a function is called “passing an argument.” In this example, the text—‘Hello world.’—is the argument. Arguments are the values you pass to a function, and correspond to the parameters defined when you create the function. Even with a really simple function like this, the logic of when and how things work can be a little confusing if you’re new to programming. Here’s how each step breaks down, as shown in the diagram in Figure 3-8: 1. The function is read by the JavaScript interpreter and stored in memory. This step just prepares the web browser to run the function later. 2. The function is called and information—“Hello world.”—is passed to the function. Chapter 3: Adding Logic and Control to Your Programs 89 FUNCTIONS: TURN USEFUL CODE INTO REUSABLE COMMANDS 3. The information passed to the function is stored in a new variable named message. This step is equivalent to var message = 'Hello world.';. 4. Finally, the function runs, printing the value stored in the variable message to the web page. FIGURE 3-8 When working with functions, you usually create the function before you use it. The print() function here is created in the first three lines of code, but the code inside the function doesn’t actually run until the last line. A function isn’t limited to a single parameter, either. You can pass any number of arguments to a function. You just need to specify each parameter in the function, like this: function functionName(parameter1, parameter2, parameter3) { // the JavaScript you want to run } And then call the function with the same number of arguments in the same order: functionName(argument1, argument2, argument3); In this example, when functionName is called, argument1 is stored in parameter1, argument2 in parameter2, and so on. Expanding on the print function from above, suppose in addition to printing a message to the web page, you want to specify an HTML tag to wrap around the message. This way, you can print the message as a headline or a paragraph. Here’s what the new function would look like: function print(message,tag) { document.write('<' + tag + '>' + message +'' + tag + '>'); } The function call would look like this: print('Hello world.', 'p'); In this example, you’re passing two arguments—'Hello world.' and 'p'—to the function. Those values are stored in the function’s two parameters—message and tag. The result is a new paragraph—Hello world.
—printed to the page. You’re not limited to passing just strings to a function either: You can send any type of JavaScript variable or value to a function. For example, you can send an array, a variable, a number, or a Boolean value as an argument. 90 JAVASCRIPT & JQUERY: THE MISSING MANUAL Retrieving Information from Functions Sometimes a function simply does something like write a message to a page, move an object across the screen, or validate the form fields on a page. Other times, you’ll want to get something back from a function: after all, the “Get me a slice of pizza” function wouldn’t be much good if you didn’t end up with some tasty pizza at the end. Likewise, a function that calculates the total cost of items in a shopping cart isn’t very useful unless the function lets you know the final total. FUNCTIONS: TURN USEFUL CODE INTO REUSABLE COMMANDS Some of the built-in JavaScript functions we’ve already seen return values. For example, the prompt() command (page 42) pops up a dialog box with a text field, and whatever the user types into the box is returned. As you’ve seen, you can then store that return value into a variable and do something with it: var answer = prompt('What month were you born?', ''); The visitor’s response to the prompt dialog box is stored in the variable answer; you can then test the value inside that variable using a conditional statement or do any of the many other things JavaScript lets you do with variables. To return a value from your own functions, you use return followed by the value you wish to return: function functionName(parameter1, parameter2) { // the JavaScript you want to run return value; } For example, say you want to calculate the total cost of a sale including sales tax. You might create a script like this: var TAX = .08; // 8% sales tax function calculateTotal(quantity, price) { var total = quantity * price * (1 + TAX); var formattedTotal = total.toFixed(2); return formattedTotal; } The first line stores the tax rate into a variable named TAX (which lets you easily change the rate simply by updating this line of code). The next three lines define the function. Don’t worry too much about what’s happening inside the function—you’ll learn more about working with numbers on page 562. The important part is the fourth line of the function—the return statement. It returns the value stored in the variable formattedTotal. To make use of the return value, you usually store it inside a variable. So in this example, you could call the function like this: var saleTotal = calculateTotal(2, 16.95); document.write('Total cost is: $' + saleTotal); Chapter 3: Adding Logic and Control to Your Programs 91 FUNCTIONS: TURN USEFUL CODE INTO REUSABLE COMMANDS In this case, the values 2 and 16.95 are passed to the function. The first number represents the number of items purchased, and the second their individual cost. The function determines the total cost plus tax and returns the total: That result is then stored into a new variable—saleTotal—which is then used as part of a document. write() command to print the total cost of the sale including tax. NOTE The return keyword should be the last statement in a function, because as soon as a browser’s JavaScript interpreter encounters the return statement, it exits the function. Any lines of code following the return statement in the function are never executed. You don’t have to store the return value into a variable, however. You can use the return value directly within another statement like this: document.write('Total: $' + calculateTotal(2, 16.95)); In this case, the function is called and its return value is added to the string 'Total: $', which is then printed to the document. At first, this way of using a function may be hard to read, so you might want to take the extra step of just storing the function’s results into a variable and then using that variable in your script. NOTE A function can only return one value. If you want to return multiple items, store the results in an array, and return the array. See page 44 for more on arrays. Keeping Variables from Colliding One great advantage of functions is that they can cut down the amount of programming you have to do. You’ll probably find yourself using a really useful function time and time again on different projects. For example, a function that helps calculate shipping and sales tax could come in handy on every order form you create, so you might copy and paste that function into other scripts on your site or on other projects. One potential problem arises when you just plop a function down into an alreadycreated script, however. What happens if the script uses the same variable names as the function? Will the function overwrite the variable from the script, or vice versa? For example: var message = 'Outside the function'; function warning(message) { alert(message); } warning('Inside the function'); // 'Inside the function' alert(message); // 'Outside the function' Notice that the variable message appears both outside the function (the first line of the script) and as a parameter in the function. A parameter is really just a variable that’s filled with data when the function’s called. In this case, the function call— warning('Inside the function');—passes a string to the function and the function 92 JAVASCRIPT & JQUERY: THE MISSING MANUAL stores that string in the variable message. It looks like there are now two versions of the variable message. So what happens to the value in the original message variable that’s created in the first line of the script? FUNCTIONS: TURN USEFUL CODE INTO REUSABLE COMMANDS You might think that the original value stored in message is overwritten with a new value, the string ‘Outside the function’; it’s not. When you run this script, you’ll see two alert dialog boxes: The first will say “Inside the function” and the second “Outside the function.” There are actually two variables named message, but they exist in separate places (Figure 3-9). FIGURE 3-9 A function parameter is only visible inside the function, so the first line of this function—function warning(message)—creates a new variable named message that can only be accessed inside the function. Once the function is done, that variable disappears. The JavaScript interpreter treats variables inside of a function differently than variables declared and created outside of a function. In programming-speak, each function has its own scope. A function’s scope is like a wall that surrounds the function—variables inside the wall aren’t visible to the rest of the script outside the wall. Scope is a pretty confusing concept when you first learn about it, but it’s very useful. Because a function has its own scope, you don’t have to be afraid that the names you use for parameters in your function will overwrite or conflict with variables used in another part of the script. So far, the only situation we’ve discussed is the use of variables as parameters. But what about a variable that’s created inside the function, but not as a parameter, like this: var message = 'Outside the function'; function warning() { var message ='Inside the function'; alert( message ); } warning(); // 'Inside the function' alert( message ); //'Outside the function' Here, the code creates a message variable twice—in the first line of the script, and again in the first line inside the function. This situation is the same as with parameters—by typing var message inside the function, you’ve created a new variable inside the function’s scope. This type of variable is called a local variable, as it’s only visible within the walls of the function—the main script and other functions can’t see or access this variable. Chapter 3: Adding Logic and Control to Your Programs 93 TUTORIAL: A SIMPLE QUIZ However, variables created in the main part of a script (outside a function) exist in global scope. All functions in a script can access variables that are created in its main body. For example, in the code below, the variable message is created on the first line of the script—it’s a global variable, and it can be accessed by the function: var message = 'Global variable'; function warning() { alert( message ); } warning(); // 'Global variable' This function doesn’t have any parameters and doesn’t define a message variable, so when the alert(message) part is run, the function looks for a global variable named message. In this case, that variable exists, so an alert dialog with the text “Global variable” appears. There’s one potential gotcha with local and global variables—a variable only exists within the function’s scope if it’s a parameter, or if the variable is created inside the function with the var keyword. Figure 3-9 demonstrates this situation. The top chunk of code demonstrates how both a global variable named message and a function’s local variable named message can exist side-by-side. The key is the first line inside the function—var message ='Inside the function';. To create a local variable, you must use var to declare the variable inside the function. Compare that to the code in the bottom half of Figure 3-10. In this case, the function doesn’t use the var keyword. Instead, the line of code message='Inside the function'; doesn’t create a new local variable; it simply stores a new value inside the global variable message. The result? The function clobbers the global variable, replacing its initial value. The notion of variable scope is pretty confusing, so the preceding discussion may not make a lot of sense for you right now. But just keep one thing in mind: If the variables you create in your scripts don’t seem to be holding the values you expect, you might be running into a scope problem. If that happens, come back and reread this section. Tutorial: A Simple Quiz Now it’s time to bring together the lessons from this chapter and create a complete program. In this tutorial, you’ll create a simple quiz system for asking questions and evaluating the quiz taker’s performance. First, this section will look at a couple of ways you could solve this problem, and discuss efficient techniques for programming. As always, the first step is to figure out what exactly the program should do. There are a few things you want the program to accomplish: 94 JAVASCRIPT & JQUERY: THE MISSING MANUAL • Ask questions. If you’re going to quiz people, you need a way to ask them questions. At this point, you know one simple way to get feedback on a web page: the prompt() command. In addition, you’ll need a list of questions; because arrays are good for storing lists of information, you’ll use an array to store your quiz questions. TUTORIAL: A SIMPLE QUIZ • Let the quiz taker know if she’s right or wrong. After you get the answer from the quiz taker, you need to determine if it’s the right answer: A conditional statement can take care of that. Then, to let the quiz taker know if she’s right or wrong, you can use the alert()command. • Print the results of the quiz. You need a way to track how well the quiz taker’s doing—a variable that keeps track of the number of correct responses will work. Then, to announce the final results of the quiz, you can either use the alert() command or the document.write() method. FIGURE 3-10 There’s a subtle yet crucial difference when assigning values to variables within a function. If you want the variable to only be accessible to the code inside the function, make sure to use the var keyword to create the variable inside the function (top). If you don’t use var, you’re just storing a new value inside the global variable (bottom). Chapter 3: Adding Logic and Control to Your Programs 95 TUTORIAL: A SIMPLE QUIZ There are many ways to solve this problem. Some beginning programmers might take a brute-force approach and repeat the same code to ask each question. For example, the JavaScript to ask the first two questions in the quiz might look like this: var answer1=prompt('How many moons if (answer1 == 1 ) { alert('Correct!'); } else { alert('Sorry. The correct answer } var answer2=prompt('How many moons if (answer2 == 31) { alert('Correct!'); } else { alert('Sorry. The correct answer } does Earth have?',''); is 1'); does Saturn have?',''); is 31'); This kind of approach seems logical because the goal of the program is to ask one question after another. However, it’s not an efficient way to program. Whenever you see the same steps written multiple times in a program, it’s time to consider using a loop or a function instead. We’ll create a program that does both: uses a loop to go through each question in the quiz, and a function that performs the question asking tasks: 1. In a text editor, open the file quiz.html. You’ll start by setting up a few variables that can track the number of correct answers and the questions for the quiz. 2. Locate the code between the GETTING JQUERY Using the jQuery CDN, you’d use this code: And the code using Google’s CDN looks like this: You only need to use one of these lines on your page, based on the CDN you prefer to use. The Google CDN seems to be the most popular, so if you’re unsure of which to use, use the Google servers. If you choose to use jQuery 2 (see the box below), just change the 1.11.0 in the above lines to 2.1.0 (or whatever number is the current version of jQuery, which you can find listed at http://jquery.com/download/). For example, to use Google’s CDN to download version 2.1.0 of jQuery you’d add this line of code: FREQUENTLY ASKED QUESTION jQuery Version 1 or 2? There are two versions of jQuery on jQuery.com—1 and 2. Which should I use? At this writing, jQuery version 1.11 and jQuery 2.1 are functionally the same. The big difference—and the reason the jQuery team released jQuery 2—is that jQuery 2 has stripped out all support for Internet Explorer 6, 7, and 8. Older versions of Internet Explorer often work differently from newer browsers and therefore require extra JavaScript programming to get new features to work. Supporting those browsers requires more code, expanding the size of the jQuery library file. In the hopes that IE 6, 7, and 8 will one day vanish from the world, the jQuery team created a leaner version of jQuery that removes all support for those browsers. However, IE 6, 7, and 8 are still in use, so jQuery version 1 is still being maintained. In fact, IE8 is still the most commonly used version of Internet Explorer. Because of that, you’ll be using jQuery version 1.11 in this book. It has all the same features as jQuery 2, but still supports older versions of Internet Explorer. Until the audience who visits your site no longer use Internet Explorer 8, you should stick with the latest release of version 1 (version 1.11 as of this writing). Going forward, any new features that the jQuery team adds to jQuery will only go into the version 2 branch of jQuery. Version 1 will only change to incorporate bug fixes. Rest assured, though, everything you learn in this book will work in both versions. However, if, after reading this book, some fantastic, new, gotta-have-it feature is added to jQuery 2, you may consider switching to that version. Chapter 4: Introducing jQuery 109 GETTING JQUERY NOTE You may have noticed that the link to the Google CDN looks a little unusual. It doesn’t begin with http:// like the Microsoft or jQuery CDN’s. This kind of URL is called protocol-relative, which simply means that the browser will load the file using the security protocol currently in use. For example, if your page is being sent over a secure server using https, then the jQuery file will also be sent securely. For more detail on protocol-relative URLs, visit www.paulirish.com/2010/the-protocol-relative-url/. There is a problem with these types of URLs: they only work when viewing a page from a web server. If you use protocol-relative URLs in local files that you just view by opening from your web browser, they won’t work. Downloading Your Own jQuery File You can easily download the jQuery file and add it to your site along with all your other web pages and files. The tutorial files you downloaded for this book as described in the note on page 12 include the jQuery library file, but since the jQuery team updates the library on a regular basis, you can find the latest version at http:// jquery.com/download/. To download the latest version of jQuery: 1. Visit http://jquery.com/download/. This page has information about the code, a list of the CDNs mentioned above, and previous versions of jQuery. 2. Select version 1.x or 2.x. This book uses version 1.11, but read the box on page 109 for more information. In a nutshell, if your site needs to work in the still widely used Internet Explorer 8, then use version 1.11. The jQuery file comes in two versions on the download site—compressed and uncompressed. The uncompressed file is very large (over 280 k), and is only provided so you can learn more about jQuery by looking at its code. The code includes lots of comments (page 58) that help make clear what the different parts of the file do. (But in order to understand the comments, you need to know a lot about JavaScript.) You should use the compressed version for your websites. The compressed version is a minified file, meaning that it’s much smaller than a regular JavaScript file: All JavaScript comments and unnecessary spaces (tabs, line breaks, and so on) are removed, making the file hard-to-read but faster to download. NOTE You can usually identify a minified JavaScript file by the appearance of .min in the filename; for example, jquery-1.11.0.min.js indicates that this file contains the minified version of version 1.11.0 of jQuery. 3. Right-click the link for the compressed file and from the menu that appears, choose Save Link As. If you just click the link, you won’t download the file. Instead, the web browser displays all the code in a browser window, so you need to use this “Save as” method. 110 JAVASCRIPT & JQUERY: THE MISSING MANUAL 4. Navigate to the folder on your computer where you keep your website and save the file. GETTING JQUERY You can save the jQuery file anywhere you want on your site, but many web designers keep their external JavaScript files in a folder that’s dedicated to the purpose. Usually the folder has a name like scripts, libs, js, or _js. FREQUENTLY ASKED QUESTION The jQuery Version Used in This Book I see that this book uses version 1.11.0 of jQuery, but the current version on the jQuery site is 1.11.x. Is this a problem? jQuery is always evolving. New bugs are often discovered, and the jQuery team works diligently to fix them. In addition, as new versions of web browsers come out with new capabilities and better support for current standards, the jQuery team updates jQuery to work most efficiently with those browsers. Finally, new features are sometimes added to jQuery to make it more useful for web programmers. For these reasons, it’s likely that you can find a newer version of jQuery than the one that’s used in this book. If there is a newer version, then by all means use it. jQuery has matured over the years and its core functionality changes very little. While the jQuery programmers are often tinkering under the hood to make jQuery faster, work better across browsers, and fix bugs, the way you use jQuery doesn’t usually change that much. In other words, while programmers might alter a jQuery function to perform better, the way you use that function—the function name, the arguments you give it, and the values it returns—don’t often change. This means that what you learn in this book will most probably work with a newer version of jQuery, but only faster and better. This isn’t always the case, however. For example, six months after the last edition of this book came out, jQuery 1.9 was released. That version eliminated a jQuery command used in some of the examples in this book, so readers who tried to use the latest version of jQuery found that a couple tutorials no longer worked. You can often tell how much different one version of jQuery is from another by the numbering scheme. The first number points to a very significant new version, like jQuery version 1 or version 2. (As discussed in the box on page 109, version 2 has the same features as version 1.11 but doesn’t support Internet Explorer 8 or earlier.) Then there are the dot releases—jQuery 1.1, 1.2, 1.3 and so on. Each of those numbers usually offers new functions, rewriting of older functions to work better, and so on. Finally, the last number, like the final 0 in jQuery 1.11.0, usually refers to some sort of bug fix (for jQuery 1.11 in this case). So if you’re using version 1.11.0 of jQuery and version 1.11.3 comes out, it’s usually a good idea to upgrade, as this will probably include fixes from problems discovered in 1.11.0. To find out what’s changed in a new version, just visit the Download page ( http://jquery.com/download/ )—and look for the link to the Release Notes for the current version. For example, the page http://blog.jquery.com/2014/01/24/jquery1-11-and-2-1-released/ discusses the release of versions 1.11.0 and 2.1. The Release Notes list changes made to that version. After reading the list of changes, you can decide for yourself if it seems worthwhile to upgrade. For example, if the changes relate to features you don’t use on your site, you can probably skip that upgrade; however, if the changes are bug fixes related to features you do use, it’s a good idea to upgrade. If you use jQuery plug-ins on your site, you’ll need to be a bit more cautious about upgrading to the latest version of jQuery, unless you’re sure the plug-in works with the new version of jQuery. Chapter 4: Introducing jQuery 111 ADDING JQUERY TO A PAGE Adding jQuery to a Page If you’re using one of the CDN versions of jQuery (page 108), you can point to it using one of the code snippets listed on page 109. For example, to use the Google CDN version of jQuery, you’d add TIP When using the Google CDN, you can leave off parts of the version number. If you use 1.11 instead of 1.11.0 in the link (), then Google loads the latest version in the 1.11 family—1.11.2, for example. If jQuery is updated to 1.11.9, then Google loads that version. This technique is smart since (as mentioned in the box on page 111) the minor version changes 1.11.0 to 1.11.2 are often bug fixes that will improve the functioning of your site. Once you’ve downloaded jQuery to your computer, you tell the web page you wish to use it on where the browser can find the file. The jQuery file is simply an external .js file, so you attach it just like any external JavaScript file, as described on page 15. For example, say you’ve stored the jquery.js file in a folder named js in your site’s root folder. To attach the file to your home page, you’d add the following script tag to the head of the page: Once you’ve attached the jQuery file, you’re ready to add your own scripts that take advantage of jQuery’s advanced functions. The next step is to add a second set of The second set of This loads the jQuery file from the site. Note that the name of the folder containing the jQuery file is _js (don’t forget the underscore character at the beginning). Next, you’ll add a set of The version number is left off in this book to make it easier to update the tutorial files with new versions of jQuery. For example, as of this writing jQuery 1.11.0 is the latest version of jQuery 1—see the box on page 109 for the difference between versions 1 and 2. But by the time you’re reading this, it might be version 1.11.1 or 1.12.0. The tutorial files will have the latest version of jQuery, so you’ll always be using the latest version. 3. Press Enter (or Return) to create a new line below the jQuery code and add the code listed in bold below: NOTE The line numbers to the left of each line of code are just for your reference. Don’t actually type them as part of the script on the web page. Now add the document.ready() function. 4. Click on the empty line between the The JavaScript comment // end ready is particularly helpful as your programs get longer and more complicated. On a long program, you’ll end up with lots of }); scattered throughout, each marking the end of an anonymous function and Chapter 4: Introducing jQuery 143 AUTOMATIC PULL QUOTES a function call. Putting a comment that identifies what the }); matches makes it much easier to later return to your code and understand what is going on. Steps 1–4 cover the basic setup for any program you’ll write using jQuery, so make sure you understand what it does. Next, you’ll get into the heart of your program by selecting the tags containing the text that should appear in the pullquote boxes. 5. Add the bolded code on line 4: 1 2 3 4 5 6 The $('span.pq') is a jQuery selector that locates every tag with a class of pq applied to it. Next you’ll add the code needed to loop through each of these tags and do something to them. 6. Add the bolded code on lines 4 and 6: 1 2 3 4 5 6 7 8 As discussed on page 138, .each() is a jQuery function that lets you loop through a selection of elements. The function takes one argument, which is an anonymous function. Next you’ll start to build the function that will apply to each matching tag on this page. Get started by creating a copy of the . 7. Add the code listed in bold on line 5 below to the script: 1 2 3 4 5 6 7 8 144 JAVASCRIPT & JQUERY: THE MISSING MANUAL This function starts by creating a new variable named quote, which contains a clone (just a copy) of the current (see page 139 if you forgot what $(this) means). The jQuery .clone() function duplicates the current element, including all of the HTML within the element. In this case, it makes a copy of the tag, including the text inside the that will appear in the pull quote box. AUTOMATIC PULL QUOTES Cloning an element copies everything, including any attributes applied to it. In this instance, the original had a class named pq. You’ll remove that class from the copy. 8. Add the two lines of code listed in bold on lines 6 and 7 below to the script: 1 2 3 4 5 6 7 8 9 10 As discussed on page 131, the removeClass() function removes a class name from a tag, while the addClass() function adds a class name to a tag. In this case, we’re replacing the class name on the copy, so you can use a CSS class named .pullquote to format the as a pull quote box. Finally, you’ll add the to the page. 9. Add the bolded line of code (line 8) to the script: 1 2 3 4 5 6 7 8 9 10 11 This line is the final piece of the function—up until this line, you’ve just been manipulating a copy of the in the web browser’s memory. No one viewing the page would see it until the copy is actually added to the DOM. Chapter 4: Introducing jQuery 145 AUTOMATIC PULL QUOTES In this case, you’re inserting the copy of the tag, just before the one in your HTML. In essence, the page will end up with HTML sort of like this: ...and that's how I discovered the Loch Ness monster. ...and that's how I discovered the Loch Ness monster. Although the text looks like it will appear duplicated side by side, the CSS formatting makes the pull quote box float to the right edge of the page. NOTE To achieve the visual effect of a pull quote box, the page has a CSS style that uses the CSS float property. The box is moved to the right edge of the paragraph in which the text appears, and the other text in the paragraph wraps around it. If you’re unfamiliar with this technique, you can learn about the CSS float property at http://css.maxdesign.com.au/floatutorial/. If you wish to examine the .pullquote style, just look in the head of the tutorial file. That style and all its properties are listed there. At this point, all of the JavaScript is complete. However, you won’t see any pull quote boxes until you massage the HTML a bit. 10. Find the firsttag in the page’s HTML. Locate a sentence and wrap around it. For example: Nullam ut nibh sed orci tempor rutrum. You can repeat this process to add pull quotes to other paragraphs as well. 11. Save the file and preview it in a web browser. The final result should look something like Figure 4-8. If you don’t see a pull quote box, make sure you added the tag in step 10 correctly. Also, check out the tips on page 18 for fixing a malfunctioning program. You can find a completed version of this tutorial in the file complete_pull-quote.html. 146 JAVASCRIPT & JQUERY: THE MISSING MANUAL CHAPTER Action/Reaction: Making Pages Come Alive with Events 5 W hen you hear people talk about JavaScript, you usually hear the word “interactive” somewhere in the conversation: “JavaScript lets you make interactive web pages.” What they’re really saying is that JavaScript lets your web pages react to something a visitor does: moving a mouse over a navigation button produces a menu of links; selecting a radio button reveals a new set of form options; clicking a small photo makes the page darken and a larger version of the photo pop onto the screen. All the different visitor actions that a web page can respond to are called events. JavaScript is an event-driven language: Without events, your web pages wouldn’t be able to respond to visitors or do anything really interesting. It’s like your desktop computer. Once you start it up in the morning, it doesn’t do you much good until you start opening programs, clicking files, making menu selections, and moving your mouse around the screen. What Are Events? Web browsers are programmed to recognize basic actions like the page loading, someone moving a mouse, typing a key, or resizing the browser window. Each of the things that happens to a web page is an event. To make your web page interactive, you write programs that respond to events. In this way, you can make a
tag appear or disappear when a visitor clicks the mouse, a new image appear when she mouses over a link, or check the contents of a text field when she clicks a form’s Submit button. 147 WHAT ARE EVENTS? An event represents the precise moment when something happens. For example, when you click a mouse, the precise moment you release the mouse button, the web browser signals that a click event has just occurred. The moment that the web browser indicates that an event has happened is when the event fires, as programmers put it. Web browsers actually fire several events whenever you click the mouse button. First, as soon as you press the mouse button, the mousedown event fires; then, when you let go of the button, the mouseup event fires; and finally, the click event fires (Figure 5-1). NOTE Understanding when and how these events fire can be tricky. To let you test out different event types, this chapter includes a demo web page with the tutorial files. Open events.html (in the testbed folder) in a web browser. Then move the mouse, click, and type to see some of the many different events that constantly occur on a web page (Figure 5-1). FIGURE 5-1 While you may not be aware of it, web browsers are constantly firing off events whenever you type, mouse around, or click. For example, double-clicking the mouse triggers two mousedown, mouseup, and onclick events, as well as the doubleclick event itself. The events.html file (included with the tutorial files in the testbed folder) shows you many of these events in action. Mouse Events Ever since Steve Jobs introduced the Macintosh in 1984, the mouse has been a critical device for all personal computers (as has the trackpad for laptops). Folks use it to open applications, drag files into folders, select items from menus, and even to 148 JAVASCRIPT & JQUERY: THE MISSING MANUAL draw. Naturally, web browsers provide lots of ways of tracking how a visitor uses a mouse to interact with a web page: WHAT ARE EVENTS? • click. The click event fires after you click and release the mouse button. You’ll commonly assign a click event to a link: For example, a link on a thumbnail image can display a larger version of that image when clicked. However, you’re not limited to just links. You can also make any tag on a page respond to an event—even just clicking anywhere on the page. NOTE The click event can also be triggered on links via the keyboard. If you tab to a link, then press the Enter (Return) key, the click event fires. • dblclick. When you press and release the mouse button twice quickly, a doubleclick (dblclick) event fires. It’s the same action you use to open a folder or file on your desktop. Double-clicking a web page isn’t a usual web-surfer action, so if you use this event, you should make clear to visitors where they can doubleclick and what will happen after they do. Also note each click in a double-click event also fires two click events, so don’t assign click and dblclick events to the same tag. Otherwise, the function for the click will run twice before the dblclick function runs. • mousedown. The mousedown event is the first half of a click—the moment when you click the button before releasing it. This event is handy for dragging elements around a page. You can let visitors drag items around your web page just like they drag icons around their desktop—by clicking on them (without releasing the button) and moving them, and then releasing the button to drop them (you’ll learn how to do this with jQuery UI on page 399). • mouseup. The mouseup event is the second half of a click—the moment when you release the button. This event is handy for responding to the moment when you drop an item that has been dragged. • mouseover. When you move your mouse over an element on a page, a mouseover event fires. You can assign an event handler to a navigation button using this event and have a submenu pop up when a visitor mouses over the button. (If you’re used to the CSS :hover pseudo-class, then you know how this event works.) • mouseout. Moving a mouse off an element triggers the mouseout event. You can use this event to signal when a visitor has moved her mouse off the page, or to hide a pop-up menu when the mouse travels outside the menu. • mousemove. Logically enough, the mousemove event fires when the mouse moves—which means this event fires all of the time. You use this event to track the current position of the cursor on the screen. In addition, you can assign this event to a particular tag on the page—a, for example—and respond only to movements within that tag. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 149 WHAT ARE EVENTS? NOTE Because the mousemove event is triggered very frequently (many times as you move the mouse), be careful assigning actions to this event. Trying to process a lengthy action in response to every mouse move can greatly slow down a program and the overall responsiveness of a web page. Document/Window Events The browser window itself understands a handful of events that fire from when the page loads to when the visitor leaves the page: • load. The load event fires when the web browser finishes downloading all of a web page’s files: the HTML file itself, plus any linked images, Flash movies, and external CSS and JavaScript files. Web designers have traditionally used this event to start any JavaScript program that manipulated the web page. However, loading a web page and all its files can take a long time if there are a lot of graphics or other large linked files. In some cases, this meant the JavaScript didn’t run for quite some time after the page was displayed in the browser. Fortunately, jQuery offers a much more responsive replacement for the load event, as described on page 160. • resize. When you resize your browser window by clicking the maximize button, or dragging the browser’s resize handle, the browser triggers a resize event. Some designers use this event to change the layout of the page when a visitor changes the size of his browser. For example, after a visitor resizes his browser window, you can check the window’s width—if the window is really wide, you could change the design to add more columns of content to fit the space. • scroll. The scroll event is triggered whenever you drag the scroll bar, or use the keyboard (for example, the up, down, home, end, and similar keys) or mouse scroll wheel to scroll a web page. If the page doesn’t have scrollbars, no scroll event is ever triggered. Some programmers use this event to help figure out where elements (after a page has scrolled) appear on the screen. NOTE Like the mousemove event (page 149), the scroll event triggers over and over again as a visitor scrolls. So again, be careful assigning any complex actions. • unload. When you click a link to go to another page, close a browser tab, or close a browser window, a web browser fires an unload event. It’s like the last gasp for your JavaScript program and gives you an opportunity to complete one last action before the visitor moves on from your page. Nefarious programmers have used this event to make it very difficult to ever leave a page. Each time a visitor tries to close the page, a new window appears and the page returns. But you can also use this event for good: For example, a program can warn a visitor about a form he’s started to fill out but hasn’t submitted, or the program could send form data to the web server to save the data before the visitor exits the page. 150 JAVASCRIPT & JQUERY: THE MISSING MANUAL Form Events In the pre-JavaScript days, people interacted with websites mainly via clicking links and filling out forms created with HTML. Entering information into a form field was really the only way for visitors to provide input to a website. Because forms are still such an important part of the web, you’ll find plenty of form events to play with: WHAT ARE EVENTS? • submit. Whenever a visitor submits a form, the submit event fires. A form might be submitted by clicking the Submit button, or simply by hitting the Enter (Return) key while the cursor is in a text field. You’ll most frequently use the submit event with form validation—to make sure all required fields are correctly filled out before the data is sent to the web server. You’ll learn how to validate forms on page 273. • reset. Although not as common as they used to be, a Reset button lets you undo any changes you’ve made to a form. It returns a form to the state it was when the page was loaded. You can run a script when the visitor tries to reset the form by using the reset event. For example, if the visitor has made some changes to the form, you might want to pop up a dialog box that asks “Are you sure you want to delete your changes?” The dialog box could give the visitor a chance to click a No button and prevent the process of resetting (erasing) the form. • change. Many form fields fire a change event when their status changes: for instance, when someone clicks a radio button, or makes a selection from a drop-down menu. You can use this event to immediately check the selection made in a menu, or which radio button was selected. • focus. When you tab or click into a text field, it gives the field focus. In other words, the browser’s attention is now focused on that page element. Likewise, selecting a radio button, or clicking a checkbox, gives those elements focus. You can respond to the focus event using JavaScript. For example, you could add a helpful instruction inside a text field—“Type your full name.” When a visitor clicks in the field (giving it focus), you can erase these instructions, so he has an empty field he can fill out. • blur. The blur event is the opposite of focus. It’s triggered when you exit a currently focused field, by either tabbing or clicking outside the field. The blur event is another useful time for form validation. For example, when someone types her email address in a text field, then tabs to the next field, you could immediately check what she’s entered to make sure it’s a valid email address. NOTE Focus and blur events also apply to links on a page. When you tab to a link, a focus event fires; when you tab (or click) off the link, the blur event fires. Keyboard Events Web browsers also track when visitors use their keyboards, so you can assign commands to keys or let your visitors control a script by pressing various keys. For example, pressing the space bar could start and stop a JavaScript animation. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 151 USING EVENTS THE JQUERY WAY Unfortunately, the different browsers handle keyboard events differently, even making it hard to tell which letter was entered! (You’ll find one technique for identifying which letter was typed on a keyboard in the Tip on page 165.) • keypress. The moment you press a key, the keypress event fires. You don’t have to let go of the key, either. In fact, the keypress event continues to fire, over and over again, as long as you hold the key down, so it’s a good way to see if a visitor is holding down the key. For example, if you created a web racecar game you could assign a key to the gas pedal. The player only has to press the key down and hold it down to make the car move. • keydown. The keydown event is like the keypress event—it’s fired when you press a key. Actually, it’s fired right before the keypress event. In Opera, the keydown event only fires once. In other browsers, the keydown event behaves just like the keypress event—it fires over and over as long as the key is pressed. • keyup. Finally, the keyup event is triggered when you release a key. Using Events the jQuery Way Traditionally, programming with events has been tricky. For a long time, Internet Explorer had a completely different way of handling events than other browsers, requiring two sets of code (one for IE and one for all other browsers) to get your code to work. Fortunately, IE9 and later use the same method for handling events as other browsers, so programming is a lot easier. However, there are still a lot of people using IE8, so a good solution that makes programming with events easy and cross-browser compatible is needed. Fortunately, you have jQuery. As you learned in the last chapter, JavaScript libraries like jQuery solve a lot of the problems with JavaScript programming—including pesky browser incompatibilities. In addition, libraries often simplify basic JavaScript-related tasks. jQuery makes assigning events and event helpers (the functions that deal with events) a breeze. As you saw on page 113, jQuery programming involves (a) selecting a page element and then (b) doing something with that element. In fact, because events are so integral to JavaScript programming, it’s better to think of jQuery programming as a three-step process: 1. Select one or more elements. The previous chapter explained how jQuery lets you use CSS selectors to choose the parts of the page you want to manipulate. When assigning events, you want to select the elements that the visitor will interact with. For example, what will a visitor click—a link, a table cell, an image? If you’re assigning a mouseover event, what page element does a visitor mouse over to make the action happen? 152 JAVASCRIPT & JQUERY: THE MISSING MANUAL 2. Assign an event. In jQuery, most DOM events have an equivalent jQuery function. So to assign an event to an element, you just add a period, the event name, and a set of parentheses. So, for example, if you want to add a mouseover event to every link on a page, you can do this: USING EVENTS THE JQUERY WAY $('a').mouseover(); To add a click event to an element with an ID of menu, you’d write this: $('#menu').click(); You can use any of the event names listed on pages page 148–152 (and a couple of jQuery-only events discussed on page 162). After adding the event, you still have some work to do. In order for something to happen when the event fires, you must provide a function for the event. 3. Pass a function to the event. Finally, you need to define what happens when the event fires. To do so, you pass a function to the event. The function contains the commands that will run when the event fires: for example, making a hiddentag visible or highlighting a moused-over element. You can pass a previously defined function’s name like this: $('#start').click(startSlideShow); When you assign a function to an event, you omit the () that you normally add to the end of a function’s name to call it. In other words, the following won’t work: $('#start').click(startSlideShow()); However, the most common way to add a function to an event is to pass an anonymous function to the event. You read about anonymous functions on page 138—they’re basically a function without a name. The basic structure of an anonymous function looks like this: function() { // your code here } The basic structure for using an anonymous function with an event is pictured in Figure 5-2. NOTE To learn more about how to work with jQuery and events, visit http://api.jquery.com/category/events/. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 153 USING EVENTS THE JQUERY WAY FIGURE 5-2 In jQuery, an event works like a function, so you can pass an argument to the event. You can think of an anonymous function, then, as an argument—like a single piece of data that’s passed to a function. If you think of it that way, it’s easier to see how all of the little bits of punctuation fit together. For example, in the last line, the } marks the end of the function (and the end of the argument passed to the mouseover function); the ) is the end of the mouseover() function; and the semicolon is the end of the entire statement that began with the selector $('a'). Here’s a simple example. Assume you have a web page with a link that has an ID of menu. When a visitor moves his mouse over that link, you want a hidden list of additional links to appear—assume that the list of links has an ID of submenu. So what you want to do is add a mouseover event to the menu, and then call a function that shows the submenu. The process breaks down into four steps: 1. Select the menu: $('#menu') 2. Attach the event: $('#menu').mouseover(); 3. Add an anonymous function: $('#menu').mouseover(function() { }); // end mouseover You’ll encounter lots of collections of closing brace, closing parenthesis, and semicolons—});—which frequently mark the end of an anonymous function inside a function call. You see them everywhere, so it’s always a good idea to add a JavaScript comment—in this example, // end mouseover—to specify what that trio of punctuation means. 4. Add the necessary actions (in this case, it’s showing the submenu): $('#menu').mouseover(function() { $('#submenu').show(); }); // end mouseover A lot of people find the crazy nest of punctuation involved with anonymous functions very confusing (that last }); is always a doozy). And it is confusing, but the 154 JAVASCRIPT & JQUERY: THE MISSING MANUAL best way to get used to the strange world of JavaScript is through lots of practice, so the following hands-on tutorial should help reinforce the ideas just presented. NOTE TUTORIAL: INTRODUCING EVENTS The show() function is discussed in the next chapter on page 184. Tutorial: Introducing Events This tutorial gives you a quick introduction to using events. You’ll make the page react to several different types of events so you can get a handle on how jQuery events work and how to use them. NOTE See the note on page 12 for information on how to download the tutorial files. 1. In a text editor, open the file events_intro.html in the chapter05 folder. You’ll start at the beginning by adding a link to the jQuery file. 2. Click in the empty line just above the closing tag and type: This line loads the jQuery file from the site. Note that the name of the folder containing the jQuery file is _js (don’t forget the underscore character at the beginning). Next, you’ll add a set of Now add the document.ready() function. 4. Click in the empty line between the Don’t forget the JavaScript comment after the });. Even though adding comments requires a little extra typing, they’ll be very helpful in identifying the different parts of a program. At this point, you’ve completed the steps you’ll follow whenever you use jQuery on your web pages. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 155 TUTORIAL: INTRODUCING EVENTS Next, it’s time to add an event. Your first goal will be simple: have an alert box appear when a visitor double clicks anywhere on the page. To begin, you need to select the element (the page in this case) that you wish to add the event to. 5. Click in the empty line inside the .ready() function and add the bolded code below: The $('html') selects the HTML element; basically, the entire browser window. Next, you’ll add an event. 6. Type .dblclick(); // end double click after the jQuery selector so your code looks like this: .dblclick() is a jQuery function that gets the browser ready to make something happen when a visitor double-clicks on the page. The only thing missing is the “make something happen” part, which requires passing an anonymous function as an argument to the dblclick() function (if you need a recap on how functions work and what “passing an argument” means, turn to page 85). 7. Add an anonymous function by typing the code in bold below: Don’t worry, the rest of this book won’t crawl through every tutorial at this glacial pace, but it’s important for you to understand what each piece of the code is doing. The function() { } is just the outer shell; it doesn’t do anything until you add programming inside the { and }. That’s the next step. 156 JAVASCRIPT & JQUERY: THE MISSING MANUAL 8. Finally, add an alert statement: TUTORIAL: INTRODUCING EVENTS If you preview the page in a web browser and double-click anywhere on the page, a JavaScript alert box with the word “ouch” should appear. If it doesn’t, double-check your typing to make sure you didn’t miss anything. NOTE After that long build-up, having “ouch” appear on the screen probably feels like a let-down. But keep in mind that the alert() part of this script is unimportant—it’s all the other code you typed that demonstrates the fundamentals of how to use events with jQuery. As you learn more about programming and jQuery, you can easily replace the alert box with a series of actions that (when a visitor double-clicks the page) moves an element across the screen, displays an interactive photo slideshow, or starts a car-racing game. Now that you’ve got the basics, you’ll try out a few other events. 1. Add the code in bold below so your script looks like this: This code selects all links on a page (that’s the $('a') part), then adds an anonymous function to the mouseover event. In other words, when someone mouses over any link on the page, something is going to happen. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 157 TUTORIAL: INTRODUCING EVENTS 2. Add two JavaScript statements to the anonymous function you added in the last step: The first line here—var message = "You moused over a link
";—creates a new variable named message and stores a string in it. The string represents an HTML paragraph tag with some text. The next line selects an element on the page with a class name of main (that’s the $('.main')) and then appends (or adds to the end of that element) the contents of the message variable. The page contains atag with the class of main, so this code simply adds “You moused over a link” to the end of that div each time a visitor mouses over a link on the page. (See page 129 for a recap of jQuery’s append() function.) 3. Save the page, preview it in a browser, and mouse over any link on the page. Each time you mouse over a link, a paragraph is added to the page (Figure 5-3). Now you’ll add one last bit of programming: when a visitor clicks on the form button on the page, the browser will change the text that appears on that button. 4. Lastly, add the code in bold below so your finished script looks like this: 158 JAVASCRIPT & JQUERY: THE MISSING MANUAL You should understand the basics here: $('#button') selects an element with the ID button (the form button in this case), and adds a click event to it, so when someone clicks the button, something happens. In this example, the words “Stop that!” appear on the button. TUTORIAL: INTRODUCING EVENTS On page 139, you saw how to use $(this) inside of a loop in jQuery. It’s the same idea inside of an event: $(this) refers to the element that is responding to the event—the element you select and attach the event to. In this case, this is the form button. (You’ll learn more about the jQuery val() function on page 253, but basically you use it to read the value from or change the value of a form element. In this example, passing the string “Stop that!” to the val() function sets the button’s value to “Stop that!”) 5. Save the page, preview it in a browser, and click the form button. The button’s text should instantly change (Figure 5-3). For an added exercise, add the programming to make the text field’s background color change to red when a visitor clicks or tabs into it. Here’s a hint: You need to (a) select the text field; (b) use the focus() event (page 259); (c) use $(this) (as in step 12) to address the text field inside the anonymous function; and (d) use the .css() function (page 134) to change the background color of the text field. You can find the answer (and a complete version of the page) in the complete_events_intro.html file in the chapter05 folder. FIGURE 5-3 jQuery makes it easy for your web pages to respond to user interaction, such as opening an alert box when the page is clicked twice, adding text to the page in response to mousing over a link, or clicking a form button. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 159 MORE JQUERY EVENT CONCEPTS More jQuery Event Concepts Because events are a critical ingredient for adding interactivity to a web page, jQuery includes some special jQuery-only functions that can make your programming easier and your pages more responsive. Waiting for the HTML to Load When a page loads, a web browser tries immediately to run any scripts it encounters. So scripts in the head of a page might run before the page fully loads—you saw this in the Moon Quiz tutorial on page 94, where the page was blank until the script asking the questions finished. Unfortunately, this phenomenon often causes problems. Because a lot of JavaScript programming involves manipulating the contents of a web page—displaying a pop-up message when a particular link is clicked, hiding specific page elements, adding stripes to the rows of a table, and so on—you’ll end up with JavaScript errors if your program tries to manipulate elements of a page that haven’t yet been loaded and displayed by the browser. The most common way to deal with that problem has been to use a web browser’s onload event to wait until a page is fully downloaded and displayed before executing any JavaScript. Unfortunately, waiting until a page fully loads before running JavaScript code can create some pretty strange results. The onload event only fires after all of a web page’s files have downloaded—meaning all images, movies, external style sheets, and so on. As a result, on a page with lots of graphics, the visitor might actually be staring at a page for several seconds while the graphics load before any JavaScript runs. If the JavaScript makes a lot of changes to the page—for example, styles table rows, hides currently visible menus, or even controls the layout of the page—visitors will suddenly see the page change before their very eyes. Fortunately, jQuery comes to the rescue. Instead of relying on the load event to trigger a JavaScript function, jQuery has a special function named ready() that waits just until the HTML has been loaded into the browser and then runs the page’s scripts. That way, the JavaScript can immediately manipulate a web page without having to wait for slow-loading images or movies. (That’s actually a complicated and useful feat—another reason to use a JavaScript library.) You’ve already used the ready() function in a few of the tutorials in this book. The basic structure of the function goes like this: $(document).ready(function() { //your code goes here }); Basically, all of your programming code goes inside this function. In fact, the ready() function is so fundamental, you’ll probably include it on every page on which you use jQuery. You only need to include it once, and it’s usually the first and last line of a script. You must place it within a pair of opening and closing tags that adds jQuery to the page. 160 JAVASCRIPT & JQUERY: THE MISSING MANUAL So, in the context of a complete web page, the function looks like this: MORE JQUERY EVENT CONCEPTSPage Title The web page content... TIP Because the ready() function is used nearly anytime you add jQuery to a page, there’s a shorthand way of writing it. You can remove the $(document).ready part, and just type this: $(function() { // do something on document ready }); AN ALTERNATIVE TO $(DOCUMENT).READY() Putting the $(document).ready() function in the of an HTML document serves to delay your JavaScript until your HTML loads. But there’s another way to do the same thing: put your JavaScript code after the HTML. For example, many web developers simply put their JavaScript code directly before the closing tag, like this:Page Title The web page content... Chapter 5: Action/Reaction: Making Pages Come Alive with Events 161 MORE JQUERY EVENT CONCEPTS In this case, there’s no need for $(document).ready(), because by the time the scripts load, the document is ready. This approach can have some major benefits. First, you don’t need to type that extra bit of code to include the .ready() function. Second, loading and running JavaScript freezes the web browser until the scripts load and finish running. If you include a lot of external JavaScript files and they take a while to download, your web page won’t display right away. For your site’s visitors, it will look like it’s taking a long time for your page to load. You may read on web design blogs that putting your scripts at the bottom of the page is the proper way to add JavaScript. However, there are also downsides to this approach. In some cases, the JavaScript code you add to a page has dramatic effects on the page’s appearance. For example, you can use JavaScript to completely re-draw a complex HTML table so it’s easier to view and navigate. Or you might take the basic typography of a page and make it look really cool (http://letteringjs.com). In these cases, if you wait until the HTML loads and displays before downloading jQuery and running your JavaScript code, your site’s visitors may see the page one way (before it’s transformed by JavaScript) and then watch it change right before their eyes. This “quick change act” can be disconcerting. In addition, if you’re building a web application that doesn’t work without JavaScript, there’s no point in showing your visitors the page’s HTML, until after the JavaScript loads—after all, the buttons, widgets, and JavaScript-powered interface tools of your web app are just useless chunks of HTML until the JavaScript powers them. So the answer to where to put your JavaScript is “it depends.” In some cases, your site will appear more responsive if you put the JavaScript after the HTML, and sometimes when you put it before. Thankfully, due to browser-caching, once one page on your site downloads the necessary JavaScript files, the other pages will have instant access to the files in the browser cache and won’t need to waste time downloading them again. In other words, don’t sweat it: if you feel like your web page isn’t displaying fast enough, then you can try moving the scripts down to the end of the page. If it helps, then go for it. But, in many cases, whether you use the .ready() function at the top of the page won’t matter at all. NOTE When building a web page on your computer and testing it directly in your web browser, you won’t encounter the problems discussed in this section. It’s only when you put your site on a web server and have to download the script and page files over a sometimes slow Internet connection that you can see whether you have any problems with the time it takes to load and display a web page. Mousing Over and Off an Element The mouseover and mouseout events are frequently used together. For example, when you mouse over a button, a menu might appear; move your mouse off the button, and the menu disappears. Because coupling these two events is so common, jQuery provides a shortcut way of referring to both. jQuery’s hover() function works just like any other event, except that instead of taking one function as an argument, it accepts two functions. The first function runs when the mouse travels over the ele- 162 JAVASCRIPT & JQUERY: THE MISSING MANUAL ment, and the second function runs when the mouse moves off the element. The basic structure looks like this: MORE JQUERY EVENT CONCEPTS $('#selector').hover(function1, function2); You’ll frequently see the hover() function used with two anonymous functions. That kind of code can look a little weird; the following example will make it clearer. Suppose when someone mouses over a link with an ID of menu, you want a (currently invisible) DIV with an ID of submenu to appear. Moving the mouse off of the link hides the submenu again. You can use hover() to do that: $('#menu').hover(function() { $('#submenu').show(); }, function() { $('#submenu').hide(); }); // end hover To make a statement containing multiple anonymous functions easier to read, move each function to its own line. So a slightly more readable version of the code above would look like this: $('#menu').hover( function() { $('#submenu').show(); }, // end mouseover function() { $('#submenu').hide(); } // end mouseout ); // end hover Figure 5-4 diagrams how this code works for the mouseover and mouseout events. FIGURE 5-4 jQuery’s hover() function lets you assign two functions at once. The first function runs when the mouse moves over the element, while the second function runs when the mouse moves off the element. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 163 MORE JQUERY EVENT CONCEPTS If the anonymous function method is just too confusing, you can still use plain old named functions (page 85) to get the job done. First, create a named function to run when the mouseover event triggers; create another named function for the mouseout event; and finally, pass the names of the two functions to the hover() function. In other words, you could rewrite the code above like this: function showSubmenu() { $('#submenu').show(); } function hideSubmenu() { $('#submenu').hide(); } $('#menu').hover(showSubmenu, hideSubmenu); If you find this technique easier, then use it. There’s no real difference between the two, though some programmers like the fact that by using anonymous functions you can keep all of the code together in one statement, instead of spread out among several different statements. NOTE Versions of jQuery prior to 1.9 included a very useful toggle() function. This function worked like hover() except for click events. You could run one set of code on the first click, and a second set of code on the second click. In other words, you could “toggle” between clicks—great for showing a page item on the first click, then closing that item on the second click. Because toggle() is no longer part of jQuery, you’ll learn how to replicate that functionality in the tutorial starting on page 174. The Event Object Whenever a web browser fires an event, it records information about the event and stores it in an event object. The event object contains information that was collected when the event occurred, like the vertical and horizontal coordinates of the mouse, the element on which the event occurred, or whether the Shift key was pressed when the event was triggered. In jQuery, the event object is available to the function assigned to handling the event. In fact, the object is passed as an argument to the function, so to access it, you just include a parameter name with the function. For example, say you want to find the X and Y position of the cursor when the mouse is clicked anywhere on a page: $(document).click(function(evt) { var xPos = evt.pageX; var yPos = evt.pageY; alert('X:' + xPos + ' Y:' + yPos); }); // end click The important part here is the evt variable. When the function is called (by clicking anywhere in the browser window), the event object is stored in the evt variable. Within the body of the function, you can access the different properties of the event 164 JAVASCRIPT & JQUERY: THE MISSING MANUAL object using dot syntax—for example, evt.pageX returns the horizontal location of the cursor (in other words, the number of pixels from the left edge of the window). MORE JQUERY EVENT CONCEPTS NOTE In this example, evt is just a variable name supplied by the programmer. It’s not a special JavaScript keyword, just a variable used to store the event object. You could use any name you want such as event or simply e. The event object has many different properties, and (unfortunately) the list of properties varies from browser to browser. Table 5-1 lists some common properties. TABLE 5-1 Every event produces an event object with various properties that you can access within the function handling the event EVENT PROPERTY DESCRIPTION pageX The distance (in pixels) of the mouse pointer from the left edge of the browser window. pageY The distance (in pixels) of the mouse pointer from the top edge of the browser window. screenX The distance (in pixels) of the mouse pointer from the left edge of the monitor. screenY The distance (in pixels) of the mouse pointer from the top edge of the monitor. shiftKey Is true if the shift key is down when the event occurs. which Use with the keypress event to determine the numeric code for the key that was pressed (see tip, next). target The object that was the “target” of the event—for example, for a click event, the element that was clicked. data A jQuery object used with the on() function to pass data to an event handling function (page 167). TIP If you access the event object’s which property with the keypress event, you’ll get a numeric code for the key pressed. If you want the specific key that was pressed (a, K, 9, and so on), you need to run the which property through a JavaScript method that converts the key number to the actual letter, number, or symbol on the keyboard: String.fromCharCode(evt.which) Stopping an Event’s Normal Behavior Some HTML elements have preprogrammed responses to events. A link, for example, usually loads a new web page when clicked; a form’s Submit button sends the form data to a web server for processing when clicked. Sometimes you don’t want the web browser to go ahead with its normal behavior. For example, when a form is Chapter 5: Action/Reaction: Making Pages Come Alive with Events 165 MORE JQUERY EVENT CONCEPTS submitted (the submit() event), you might want to stop the form data from being sent if the person filling out the form left out important data. You can prevent the web browser’s normal response to an event with the preventDefault() function. This function is actually a part of the event object (see the previous section), so you’ll access it within the function handling the event. For example, say a page has a link with an ID of menu. The link actually points to another menu page (so visitors with JavaScript turned off will be able to get to the menu page). However, you’ve added some clever JavaScript, so when a visitor clicks the link, the menu appears right on the same page. Normally, a web browser would follow the link to the menu page, so you need to prevent its default behavior, like this: $('#menu').click(function(evt){ // clever javascript goes here evt.preventDefault(); // don't follow the link }); Another technique is simply to return the value false at the end of the event function. For example, the following is functionally the same as the code above: $('#menu').click(function(evt){ // clever javascript goes here return false; // don't follow the link }); Removing Events At times, you might want to remove an event that you had previously assigned to a tag. jQuery’s off() function lets you do just that. To use it, first create a jQuery object with the element you wish to remove the event from. Then add the off() function, passing it a string with the event name. For example, if you want to prevent all tags with the class tabButton from responding to any click events, you can write this: $('.tabButton').off('click'); Take a look at a short script to see how the off() function works. 1 2 3 4 5 6 $('a').mouseover(function() { alert('You moved the mouse over me!'); }); $('#disable').click(function() { $('a').off('mouseover'); }); Lines 1–3 add a function to the mouseover event for all links ( tags) on the page. Moving the mouse over the link opens an alert box with the message “You moved your mouse over me!” However, because the constant appearance of alert messages would be annoying, lines 4–6 let the visitor turn off the alert. When the visitor clicks a tag with an ID of disable (a form button, for example), the mouseover events are unbound from all links, and the alert no longer appears. 166 JAVASCRIPT & JQUERY: THE MISSING MANUAL If you want to remove all events from an element, don’t give the off() function any arguments. For example, to remove all events—mouseover, click, dblclick, and so on—from a submit button, you could write this code: ADVANCED EVENT MANAGEMENT $('input[type="submit"]').off(); This is a pretty heavy-handed approach, however, and in most cases you won’t want to remove all event handlers from an element. NOTE For more information on jQuery’s off() function, visit http://api.jquery.com/off/. POWER USERS’ CLINIC Stopping an Event in Its Tracks The event model lets an event pass beyond the element that first receives the event. For example, say you’ve assigned an event handler for click events on a particular link; when you click the link, the click event fires and a function runs. The event, however, doesn’t stop there. Each ancestor element (a tag that wraps around the element that’s clicked) can also respond to that same click. So if you’ve assigned a click event helper for atag that the link is inside, the function for thattag’s event will run as well. You probably won’t encounter this situation too frequently, but when you do, the results can be disconcerting. Suppose in the example in the previous paragraph, you don’t want theto do anything when the image is clicked. In this case, you have to stop the click event from passing on to thetag without stopping the event in the function that handles the click event on the image. In other words, when the image is clicked, the function assigned to the image’s click event should swap in a new graphic, but then stop the click event. This concept, known as event bubbling , means that more than one element can respond to the same action. Here’s another example: Say you add a click event to an image so when the image is clicked, a new graphic replaces it. The image is inside atag to which you’ve also assigned a click event. In this case, an alert box appears when theis clicked. Now when you click the image, both functions will run. In other words, even though you clicked the image, thealso receives the click event. The stopPropagation() function prevents an event from passing onto any ancestor tags. The function is a method of the event object (page 164), so you access it within an eventhandling function: $('#theLink').click(function(evt) { // do something evt.stopPropagation(); // stop event from continuing }); Advanced Event Management You can live a long, happy programming life using just the jQuery event methods and concepts discussed on the previous pages. But if you really want to get the most out of jQuery’s event-handling techniques, then you’ll want to learn about the on() function. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 167 ADVANCED EVENT MANAGEMENT NOTE If your head is still aching from the previous section, you can skip ahead to the tutorial on page 174 until you’ve gained a bit more experience with event handling. The on() method is a more flexible way of dealing with events than jQuery’s eventspecific functions like click() or mouseover(). It not only lets you specify an event and a function to respond to the event, but also lets you pass additional data for the event-handling function to use. This lets different elements and events (for example, a click on one link, or a mouseover on an image) pass different information to the same event-handling function—in other words, one function can act differently based on which event is triggered. NOTE As jQuery has evolved, the names used to add and remove events to elements have changed quite a bit. If you’re reading older books or blog posts, you might run into function names like bind(), live(), and delegate(). Those have all been replaced with the on() function to add events to elements. In addition, the off() function replaces the older unbind() function for removing events from elements. The basic format of the on() function is the following: $('#selector').on('click', selector, myData, functionName); The first argument is a string containing the name of the event (like click, mouseover, or any of the other events listed on pages 148–152). The second argument is optional, so you don’t have to provide a value for this argument when you use the on() function. If you do supply the argument, it must be a valid selector like tr, .callout, or #alarm. NOTE You can use that second argument to apply the event to a different element within the selected element. That technique is called event delegation, and you’ll learn about it in a bit on page 171. The third argument is the data you wish to pass to the function—either an object literal or a variable containing an object literal. An object literal (discussed on page 136) is basically a list of property names and values: { firstName : 'Bob', lastName : 'Smith' } You can store an object literal in a variable like so: var linkVar = {message:'Hello from a link'}; The fourth argument passed to the on() function is another function—the one that does something when the event is triggered. The function can either be an anonymous function or named function—in other words, this part is the same as when using a regular jQuery event, as described on page 152. 168 JAVASCRIPT & JQUERY: THE MISSING MANUAL NOTE Passing data using the on() function is optional. If you want to use on() merely to attach an event and function, then leave the data variable out: ADVANCED EVENT MANAGEMENT $('selector').on('click', functionName); This code is functionally the same as: $('selector').click(functionName); Suppose you wanted to pop up an alert box in response to an event, but you wanted the message in the alert box to be different based on which element triggered the event. One way to do that would be to create variables with different object literals inside, and then send the variables to the on() function for different elements. Here’s an example: var linkVar = { message:'Hello from a link'}; var pVar = { message:'Hello from a paragraph'}; function showMessage(evt) { alert(evt.data.message); } $('a').on('mouseover',linkVar,showMessage); $('p').on('click',pVar,showMessage); Figure 5-5 breaks down how this code works. It creates two variables, linkVar on the first line and pVar on the second line. Each variable contains an object literal, with the same property name, message, but different message text. A function, showMessage(), takes the event object (page 164) and stores it in a variable named evt. That function runs the alert() command, displaying the message property (which is itself a property of the event object’s data property). Keep in mind that message is the name of the property defined in the object literal. Other Ways to Use the on() Function jQuery’s on() function gives you a lot of programming flexibility. In addition to the techniques listed in the previous section, it also lets you tie two or more events to the same function. For example, say you write a program that makes a large image appear on the screen when a visitor clicked a thumbnail image (the common “lightbox” effect found on thousands of websites). You want the larger image to disappear when the visitor either clicks anywhere on the page or hits any key on the keyboard (providing both options makes your program respond to people who prefer the keyboard over the mouse and vice versa). Here’s some code that does that: $(document).on('click keypress', function() { $('#lightbox').hide(); }); // end on The important part is 'click keypress'. By providing multiple event names, each separated by a space, you’re telling jQuery to run the anonymous function when any of the events in the list happen. In this case, when either the click or keypress event fires on the document. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 169 ADVANCED EVENT MANAGEMENT FIGURE 5-5 jQuery’s on() function lets you pass data to the function responding to the event. That way, you can use a single named function for several different elements (even with different types of events), while letting the function use data specific to each event helper. 170 JAVASCRIPT & JQUERY: THE MISSING MANUAL In addition, if you want to attach several events that each trigger different actions, you don’t need to use the on() function multiple times. In other words, if you want to make one thing happen when a visitor clicks an element, and another when a visitor mouses over that same element, you might be tempted to write this: ADVANCED EVENT MANAGEMENT $('#theElement').on('click', function() { // do something interesting }); // end on $('#theElement').on('mouseover', function() { // do something else interesting }); // end on You can do the same thing by passing an object literal (page 136) to the on() function that is composed of an event name, followed by a colon, followed by an anonymous function. Here’s the code above rewritten, calling the on() function only once and passing it an object literal (in bold): $('#theElement').on({ 'click' : function() { // do something interesting }, // end click function 'mouseover' : function() { // do something interesting } // end mouseover function }); // end on Delegating Events with on() As mentioned on page 167, the on() method can accept a second argument, which is another selector: $('#selector').on('click', selector, myData, functionName); That second argument can be any valid jQuery selector, like an ID, class, element, or any of the selectors discussed on page 119. Passing a selector to the on() function significantly changes how on() works. Without passing a selector, the event is applied to the initial selector—$('#selector')—in the example above. Say you added this code to a page: $('li').on('click', function() { $(this).css('text-decoration': 'line-through'); }); // end on This code adds a line through the text in every- tag that a visitor clicks. Remember that, in this case, $(this) refers to the element that’s handling the event—the clicked
- tag. In other words, the click event is “bound” to the
- tag. In most cases, that’s exactly what you want to do—define a function that runs when the visitor interacts with a specific element. You can have the function run when a visitor clicks a link, mouses over a menu item, submits a form, and so on. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 171 ADVANCED EVENT MANAGEMENT NOTE Still not sure what $(this) stands for? See page 139 for an in-depth discussion, and page 159 for details on how $(this) works with event handlers. However, there’s one problem with this method of attaching event handlers to elements: it only works if the element is already on the page. If you dynamically add HTML after you add an event handler like click(), mouseover(), or on(), those new elements won’t have any event handlers attached to them. OK, that’s a mindful. Here’s an example to make it clearer. Imagine you’ve created a To-Do List application that lets a visitor manage a list of tasks. When the application first loads, there’s nothing in the list (#1 in Figure 5-6). A visitor can fill out a text field and click an Add Task button to add more tasks to the list (#2 in Figure 5-6). After the visitor finishes a task, she can click that task to mark it done (#3 in Figure 5-6). To mark a task done, you know you need to add a click event to each
- tag so when it’s clicked, the
- is marked as done in some way. In Figure 5-6, a completed task is grayed-out and has a line through it. The problem is that when the page loads there are no
- tags, so adding a click event handler to every
- tag won’t have any effect. In other words, the code on page 171 won’t work. NOTE Note: You can learn more about jQuery event delegation at http://api.jquery.com/on/. Instead, you have to delegate the events, which means applying an event to a parent element higher up in the chain (an element that already exists on the page) and then listening for events on particular child elements. Because the event is applied to an already existing element, adding new children won’t interfere with this process. In other words, you’re delegating the task of listening to events to an already existing parent element. For a more detailed explanation, see the box on page 175. Meanwhile, here’s how you can use the on() function to make this particular example work: $(‘ul’).on(‘click’, ‘li’, function() { $(this).css(‘text-decoration’: ‘line-through’); }); // end on When you created the page, you added an empty
tag as a container for adding each new task inside an
- tag. As a result, when the page loads, one empty
tag is already in place. Then, running the above code adds the on() function to that tag. The visitor hasn’t yet added any to-do list items, so there are no
- tags. However, when you add the selector ‘li’ as the second argument in the on() function, you’re saying that you want to listen to click events not on the
tag but on any
- tags inside that unordered list. It doesn’t matter when the
- tags are added to the page because the
tag is the one doing the event listening. 172 JAVASCRIPT & JQUERY: THE MISSING MANUAL ADVANCED EVENT MANAGEMENT FIGURE 5-6 Sometimes you’ll write JavaScript code that dynamically adds new HTML to a page. In this example, visitors can add new items (tasks, in this example) to an unordered list. When the page first loads there are no items in the list, just an empty pair of
tags (top). As a visitor types in new tasks and clicks the Add Task button, new
- tags are added to the page (middle). To mark a task done, just click the task in the list (bottom). You’ll find this working example in the tutorial file to-do-list.html in the chapter05 folder. Chapter 5: Action/Reaction: Making Pages Come Alive with Events 173 TUTORIAL: A ONE-PAGE FAQ HOW EVENT DELEGATION AFFECTS THE $(THIS) OBJECT As mentioned earlier, the $(this) object refers to the element that’s currently being handled within a loop (page 139) or by an event handler (page 159). Normally, in an event handler, $(this) refers to the initial selector. For example: $('ul').on('click', function() { $(this).css('text-decoration': 'line-through'); } In the above code, $(this) refers to the
tag the visitor clicks. However, when you use event delegation, the initial selector is no longer the element that’s being interacted with—it’s the element that contains the element the visitor clicks on (or mouses over, tabs to, and so on). Take a look at the event delegation code one more time: $('ul').on('click', 'li', function() { $(this).css('text-decoration': 'line-through'); }); // end on In this case, the
- tag is the one the visitor will click, and it’s the element that needs to respond to the event. In other words,
is just the container, and the function needs to be run when the
- tag is clicked. So, in this example, $(this) is going to refer to the
- tag, and the function above will add a line through each
- tag the visitor clicks. For many tasks, you won’t need event delegation at all. However, if you ever need to add events to HTML that isn’t already on the page when it loads, then you’ll need to use this technique. For example, when you use Ajax (Chapter 13), you may need to use event delegation to apply events to HTML content that’s dynamically added to a web page from a web server. NOTE In some cases, you may want to use event delegation simply to improve JavaScript performance. If you’re adding lots and lots of tags to the same event handler, for example, hundreds of table cells in a large table, it’s often better to delegate the event to the