(This page has no text content)
(This page has no text content)
JavaScript Cookbook Shelley Powers Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
JavaScript Cookbook by Shelley Powers Copyright © 2010 Shelley Powers. 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://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Simon St.Laurent Production Editor: Adam Zaremba Copyeditor: Colleen Toporek Proofreader: Kiel Van Horn Indexer: Potomac Indexing, LLC Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: July 2010: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. JavaScript Cookbook, the image of a lesser egret, and related trade dress are trade- marks 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, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-0-596-80613-2 [SB] 1278088163
Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Working with JavaScript Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Concatenating Two or More Strings 3 1.2 Concatenating a String and Another Data Type 4 1.3 Conditionally Comparing Strings 5 1.4 Finding a Substring in a String 8 1.5 Extracting a Substring from a String 9 1.6 Checking for an Existing, Nonempty String 10 1.7 Breaking a Keyword String into Separate Keywords 13 1.8 Inserting Special Characters 15 1.9 Processing Individual Lines of a textarea 16 1.10 Trimming Whitespace from the Ends of a String 17 1.11 Left- or Right-Pad a String 19 2. Using Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2.1 Testing Whether a Substring Exists 24 2.2 Testing for Case-Insensitive Substring Matches 25 2.3 Validating a Social Security Number 26 2.4 Finding and Highlighting All Instances of a Pattern 28 2.5 Replacing Patterns with New Strings 31 2.6 Swap Words in a String Using Capturing Parentheses 32 2.7 Using Regular Expressions to Trim Whitespace 35 2.8 Replace HTML Tags with Named Entities 36 2.9 Searching for Special Characters 37 3. Dates, Time, and Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.1 Printing Out Today’s Date 41 3.2 Printing Out the UTC Date and Time 42 3.3 Printing Out an ISO 8601 Formatted Date 43 v
3.4 Converting an ISO 8601 Formatted Date to a Format Acceptable to the Date Object 45 3.5 Creating a Specific Date 47 3.6 Scheduling a Future Date 48 3.7 Tracking Elapsed Time 49 3.8 Creating a Timeout 49 3.9 Creating Recurring Timers 50 3.10 Using Function Closures with Timers 52 4. Working with Numbers and Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.1 Keeping an Incremental Counter 57 4.2 Converting a Decimal to a Hexadecimal Value 59 4.3 Creating a Random Number Generator 59 4.4 Randomly Generating Colors 60 4.5 Converting Strings in a Table to Numbers 61 4.6 Summing All Numbers in a Table Column 62 4.7 Converting Between Degrees and Radians 64 4.8 Find the Radius and Center of a Circle to Fit Within a Page Element 65 4.9 Calculating the Length of a Circular Arc 67 5. Working with Arrays and Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.1 Looping Through an Array 71 5.2 Creating a Multidimensional Array 71 5.3 Creating a String from an Array 73 5.4 Sorting an Array 74 5.5 Store and Access Values in Order 75 5.6 Store and Access Values in Reverse Order 76 5.7 Create a New Array as a Subset of an Existing Array 77 5.8 Searching Through an Array 78 5.9 Flatten a Multidimensional Array 79 5.10 Search and Remove or Replace Array Elements 80 5.11 Applying a Function Against Each Array Element 82 5.12 Applying a Function to Every Element in an Array and Returning a New Array 83 5.13 Creating a Filtered Array 84 5.14 Validating Array Contents 86 5.15 Using an Associative Array to Store Form Element Names and Values 88 6. Building Reusability with JavaScript Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 6.1 Creating a Block of Reusable Code 94 6.2 Passing Single Data Values to and from a Function 95 6.3 Passing Complex Data Objects to a Function 96 vi | Table of Contents
6.4 Creating a Dynamic Runtime Function 98 6.5 Passing a Function As an Argument to Another Function 100 6.6 Implementing a Recursive Algorithm 101 6.7 Create a Function That Remembers Its State 103 6.8 Improving Application Performance with a Generalized Currying Function 107 6.9 Improve Application Performance with Memoization (Caching Calculations) 109 6.10 Using an Anonymous Function to Wrap Global Variables 112 7. Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 7.1 Detecting When the Page Has Finished Loading 117 7.2 Capturing the Location of a Mouse Click Event Using the Event Object 119 7.3 Creating a Generic, Reusable Event Handler Function 122 7.4 Canceling an Event Based on Changed Circumstance 125 7.5 Preventing an Event from Propagating Through a Set of Nested Elements 126 7.6 Capturing Keyboard Activity 129 7.7 Using the New HTML5 Drag-and-Drop 132 7.8 Using Safari Orientation Events and Other Mobile Development Environments 140 8. Browser Pieces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 8.1 Ask the Web Page Reader to Confirm an Action 144 8.2 Creating a New, Stripped-Down Browser Window 144 8.3 Finding Out About the Browser Accessing the Page 145 8.4 Warning the Web Page Reader About Leaving a Page 146 8.5 Changing Stylesheets Depending on Color Support 147 8.6 Modifying Image Dimensions Depending on Page Size 149 8.7 Creating Breadcrumbs in a CMS Template Page 150 8.8 Bookmarking a Dynamic Page 153 8.9 Preserving State for Back Button, Page Refresh 156 9. Form Elements and Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 9.1 Accessing Form Text Input Values 159 9.2 Dynamically Disabling and Enabling Form Elements 161 9.3 Getting Information from a Form Element Based on an Event 161 9.4 Performing an Action When a Radio Button Is Clicked 164 9.5 Checking for a Valid Phone Number 166 9.6 Canceling a Form Submission 167 9.7 Preventing Duplicate Form Submissions 169 9.8 Hiding and Displaying Form Elements 171 Table of Contents | vii
9.9 Modifying a Selection List Based on Other Form Decisions 173 10. Debugging and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 10.1 Gracefully Handling No JavaScript Support 177 10.2 Checking for Errors in Functions 180 10.3 Using an Alert for Simple Debugging 181 10.4 Catching an Error and Providing Graceful Error Handling 182 10.5 Initiating Manageable Errors 184 10.6 Using Firebug with Firefox 185 10.7 Setting a Breakpoint and Examining Data with Firebug 188 10.8 Firefox and the Console 190 10.9 Using IE’s Built-in Debugger 194 10.10 Setting a Breakpoint with IE Developer Tools 196 10.11 Opera’s Dragonfly 198 10.12 Setting a Breakpoint with Dragonfly 201 10.13 Turning on Safari’s Development Tools 201 10.14 Setting a Breakpoint with Safari’s Debugger 207 10.15 Debugging in Chrome 208 11. Accessing Page Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 11.1 Access a Given Element and Find Its Parent and Child Elements 214 11.2 Accessing All Images in the Web Page 216 11.3 Discover All Images Within an Article 221 11.4 Discover all Images in Articles Using the Selectors API 222 11.5 Finding the Parent Element for a Group of Elements 226 11.6 Highlighting the First Paragraph in Every Element 227 11.7 Apply a Striping Theme to an Unordered List 230 11.8 Creating an Array of All Elements of a Given Class 231 11.9 Finding All Elements That Share an Attribute 232 11.10 Finding All Checked Options 233 11.11 Summing All the Values in a Table Row 234 11.12 Get Element Attributes 237 11.13 Get Style Information for an Element 238 12. Creating and Removing Elements and Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 12.1 Using innerHTML: A Quick and Easy Approach to Adding Content 241 12.2 Inserting Elements Before Existing Page Elements 242 12.3 Appending a New Element to the End of a Page 246 12.4 Triggering Older Versions of IE to Style New Elements 247 12.5 Inserting a New Paragraph 248 12.6 Adding Text to a New Paragraph 249 12.7 Adding Attributes to an Existing Element 251 viii | Table of Contents
12.8 Testing for a Boolean Attribute 252 12.9 Removing an Attribute 253 12.10 Moving a Paragraph 254 12.11 Replacing Links with Footnote Bullets 254 12.12 Adding Rows to an Existing Table 257 12.13 Removing a Paragraph from a div Element 260 12.14 Deleting Rows from an HTML Table 262 12.15 Changing the Element’s CSS Style Properties 264 13. Working with Web Page Spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 13.1 Determining the Area of the Web Page 270 13.2 Measuring Elements 272 13.3 Locating Elements in the Page 273 13.4 Hiding Page Sections 276 13.5 Creating Collapsible Form Sections 277 13.6 Adding a Page Overlay 281 13.7 Creating Tab Pages 284 13.8 Creating Hover-Based Pop-up Info Windows 289 13.9 Collapsing or Resizing the Sidebar 292 14. Creating Interactive and Accessible Effects with JavaScript, CSS, and ARIA . . . . . . 297 14.1 Displaying a Hidden Page Section 299 14.2 Creating an Alert Message 300 14.3 Highlighting Form Field with Missing or Incorrect Data 302 14.4 Adding Keyboard Accessibility to a Page Overlay 308 14.5 Creating Collapsible Form Sections 312 14.6 Displaying a Flash of Color to Signal an Action 316 14.7 Adding ARIA Attributes to a Tabbed Page Application 320 14.8 Live Region 323 15. Creating Media Rich and Interactive Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 325 15.1 Creating Basic Shapes in Canvas (Using the canvas Element) 326 15.2 Implementing Canvas Applications in IE 328 15.3 Creating a Dynamic Line Chart in Canvas 330 15.4 Adding JavaScript to an SVG File 333 15.5 Accessing SVG from Web Page Script 335 15.6 Emulating SVG in Internet Explorer 338 15.7 Enable Interactive SVG Embedded in HTML 339 15.8 Using the Math Functions to Create a Realistic, Ticking Analog Clock in SVG 345 15.9 Integrating SVG and the Canvas Element in HTML 347 15.10 Turning on WebGL Support in Firefox and WebKit/Safari 350 15.11 Running a Routine When an Audio File Begins Playing 351 Table of Contents | ix
15.12 Controlling Video from JavaScript with the video Element 353 16. JavaScript Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 16.1 Defining a Basic JavaScript Object 360 16.2 Keeping Object Members Private 361 16.3 Expanding Objects with prototype 362 16.4 Adding Getter/Setter to Objects 364 16.5 Inheriting an Object’s Functionality 366 16.6 Extending an Object by Defining a New Property 369 16.7 Enumerating an Object’s Properties 374 16.8 Preventing Object Extensibility 377 16.9 Preventing Object Additions and Changes to Property Descriptors 379 16.10 Preventing Any Changes to an Object 380 16.11 One-Off Objects and Namespacing Your JavaScript 381 16.12 Rediscovering “this” with Prototype.bind 383 16.13 Chaining Your Object’s Methods 385 17. JavaScript Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 17.1 Packaging Your Code 390 17.2 Testing Your Code with JsUnit 392 17.3 Minify Your Library 397 17.4 Hosting Your Library 397 17.5 Using an External Library: Building on the jQuery Framework 400 17.6 Using Existing jQuery Plug-ins 402 17.7 Convert Your Library to a jQuery Plug-in 404 17.8 Safely Combining Several Libraries in Your Applications 408 18. Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 18.1 Accessing the XMLHttpRequest Object 414 18.2 Preparing the Data for Transmission 416 18.3 Determining the Type of Query Call 417 18.4 Adding a Callback Function to an Ajax Request 420 18.5 Checking for an Error Condition 421 18.6 Processing a Text Result 422 18.7 Making an Ajax Request to Another Domain (Using JSONP) 422 18.8 Populating a Selection List from the Server 424 18.9 Using a Timer to Automatically Update the Page with Fresh Data 427 18.10 Communicating Across Windows with PostMessage 430 19. Working with Structured Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 19.1 Process an XML Document Returned from an Ajax Call 436 19.2 Extracting Pertinent Information from an XML Tree 437 19.3 Generate a JavaScript Object with JSON, Old-School Style 442 x | Table of Contents
19.4 Parse a JSON Formatted String 444 19.5 Convert an Object to a Filtered/Transformed String with JSON 445 19.6 Convert hCalendar Microformat Annotations into a Canvas Timeline 447 19.7 Glean Page RDFa and Convert It into JSON Using rdfQuery and the jQuery RDF Plug-in 450 20. Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 20.1 Attaching Persistent Information to URLs 458 20.2 Creating a Cookie to Persist Information Across Pages 462 20.3 Persisting Information Using the History.pushState Method and window.onpopevent 465 20.4 Using sessionStorage for Client-Side Storage 469 20.5 Creating a localStorage Client-Side Data Storage Item 476 20.6 Persisting Data Using a Relational Data Store 479 21. JavaScript Outside the Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483 21.1 Creating a Browser Add-0n, Plug-in, or Extension 484 21.2 Creating Desktop and Mobile Widgets 489 21.3 Creating JavaScript Applications for the iPhone, Android, and BlackBerry with PhoneGap 494 21.4 Enhancing Tools with JavaScript 496 21.5 Creating Efficient Desktop Applications with Web Workers and the File API 500 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511 Table of Contents | xi
(This page has no text content)
Preface I wrote my first book on JavaScript 15 years ago, and had to scramble just to find enough material to fill a book. With the JavaScript Cookbook, I had to choose among hundreds of uses to determine what to include. After all these years of watching JavaScript grow, I am still surprised at how far-reaching the use of JavaScript has become. In my opinion, there is no more useful programming language or development tool. About the only technology with wider use is HTML. This book is for those who have dabbled with JavaScript and wish to try out new techniques, or increase their grasp of both fundamentals and advanced features of JavaScript. Along the way, I’ll demonstrate how to: • Work with the JavaScript objects, such as String, Array, Number, and Math • Create reusable objects • Query and create new elements in the Document Object Model (DOM) • Use the new Selectors API for efficient and targeted querying • Use JavaScript with new HTML5 technologies, such as the new media elements, video and audio • Create interactive applications • Manage your web page space • Store data in various ways, from the simple to the complex • Use JavaScript with Scalable Vector Graphics (SVG) and the canvas element • Work with some of the interesting data structures, like Microformats and RDFa • Package your library for others to use, as well as use other libraries in your applications • Ensure your JavaScript applications are accessible through the use of Accessible Rich Internet Applications (ARIA) • Work in environments other than the typical desktop browser, such as creating mobile phone web applications, or extending Photoshop with new behaviors • Use and create jQuery plug-ins • Develop Ajax applications xiii
• Debug your applications using your browser’s debugger • Work with the new HTML5 drag-and-drop • Communicate using the new HTML5 cross-documentation techniques • Implement concurrent programming with Web Workers • Use the File API to access a desktop file directly in client-side JavaScript It’s not a complete encyclopedia of JavaScript use today—no one book can cover all there is to cover. But hopefully, you’ll come away with an appreciation of all you can do with JavaScript. Bon appetit! Audience, Assumptions, and Approach Readers of this book should have some exposure to web development, and the use of JavaScript. In addition, the recipe format means I’ll be focusing on specific tasks, rather than providing an overall general introduction. I won’t cover every last aspect of a JavaScript topic, such as Strings. Instead, I’ll focus on the more common tasks, or challenges, associated with the topic. There will be lots of code, some of it in code snippets, some in full-page applications. The recipes are also cross-referenced, so if I mention a specific topic in one recipe that was covered in another, I’ll include this information in the “See Also” section for the recipe. To assist you, I’ve also created example code for all of the recipes that you can download and work with immediately. Target Browsers Throughout the book, I’ll mention the target browsers. The majority of example code in this book has been designed for, and tested to work with, the latest releases of the most commonly used browsers: • Firefox 3.6x on Mac and Windows • Safari 4.0x on Mac and Windows • Opera 10.x on Mac and Windows • Chrome 5.x on Windows • Internet Explorer 8 on Windows I didn’t have a Linux machine to test for that environment, but, knock on wood, most of the recipes should work in a Linux environment with Firefox. I also didn’t have a System 7 for testing the IE9 preview, but most of the applications should work, in- cluding those using SVG (a new addition for IE9). Some of the recipes required a specialized environment, such as a mobile device or emulator, or beta (or alpha) release of the browser. I made a note where an example xiv | Preface
would not work with the target browsers, or required a specialized environment or browser. In addition, I’m introducing several new technologies and APIs that are only implemented in alpha/beta releases of certain of the browsers. Again, I included a note about browser support. Many of the examples won’t work with IE6. Before I even began the book I decided not to provide support for IE6—including any workaround code. Many major sites no longer support this far too old and too insecure browser, including Amazon, Google, YouTube, and Facebook. In addition, the workarounds necessary for IE6 are so well- known and so well-documented online, that I felt it wasn’t necessary to also include coverage in this book. Most of the examples that work with IE8 will work with IE7, with some exceptions. IE7 doesn’t support getAttribute/setAttribute on the common attributes, such as style, id, and class, and doesn’t support hasAttribute at all. In addition, IE7 doesn’t support either the CSS selectors, or the Selectors API methods, such as docu ment.querySelectorAll (covered in Chapter 11). Where IE7 doesn’t work, either I provide IE7-specific workarounds in comments in the example code you can download, or I make a note about nonsupport in the recipe— or both. Sample Code Conventions There are many code snippets and full-page examples all throughout the book. Most are based in HTML, but there are some that are based in XHTML, the XML serialization of HTML. In addition, most of the examples are based in HTML5, though I’ve also used a couple of other HTML versions, especially with the SVG examples: HTML5 <!DOCTYPE html> XHTML5 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> XHTML+SVG <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"> There’s only a couple of differences in the samples based on the HTML version. If the example is X/HTML5, you don’t need a type attribute for either the style or script elements. Additionally, in many of the XHTML sample pages, I surround the code with a CDATA section, like the following: <script> //<![CDATA[ Preface | xv
... //--><!]]> </script> The reason for using a CDATA section for the script block in XHTML is that characters such as the angle bracket (< >) and ampersand (&) are meaningful in JavaScript, but they’re also meaningful as markup. When an XML parser sees the characters, it wants to interpret them as markup. To prevent this, the CDATA section tells the parser to ignore the section. I tried to keep all of the style settings and script in the same page to simplify the ex- amples. However, in the real world, you’ll want to separate your stylesheet and script into separate files, as much as possible. Doing so keeps your HTML files clean, and makes it easy to change both style and script. Approach In the book, I cover basic JavaScript functionality that’s been around since the dawn of time, and is still essential for application development. I also include recipes covering some of the newer functionality, including working with the canvas element, trying out the new cross-domain widget communication technique (postMessage), working with the new File API and Web Workers, integrating your code with the popular jQuery library—even working with the new HTML video and audio elements (which was a lot of fun). I also introduce some of the newer uses of JavaScript, such as in mobile devices and offline desktop applications, as well as the different forms of data storage, and accessing metadata such as Microformats and RDFa in the web page. Organization The book is a relatively esoteric blend of topics, primarily covering those areas where I’ve seen both interest and growth in the last few years. I also include an introduction to the new ECMAScript 5 and HTML5 innovations. However, this book does consist of two rather general sections: the first focuses on existing JavaScript functionality and objects; the second focuses more on JavaScript used within environments, such as a browser. If you’re relatively new to JavaScript, I recommend working through all of the recipes in the first 10 chapters before tackling the recipes later in the book. Following is a chapter breakdown of the book: Chapter 1, Working with JavaScript Strings Covers some of the more commonly occurring String tasks, such as concatenating strings, trimming white space, breaking strings into tokens, as well as finding sub- strings within strings. xvi | Preface
Chapter 2, Using Regular Expressions Demonstrates the use of regular expressions, as well as working with the JavaScript RegExp object. Recipes include basic how-tos such as swapping words, replacing HTML tags with named entities, validating a Social Security number (and other patterned objects), and globally replacing values. Chapter 3, Dates, Time, and Timers Describes how to access dates and times, as well as how to format date strings, track elapsed time, find a future date, and using both the new and old ISO 8601 JavaScript functionality. The chapter also introduces JavaScript timers and work- ing with timers and function closures. Chapter 4, Working with Numbers and Math Includes basic number functionality, such as keeping an incremental counter and including conversions between hexadecimals and decimals, generating random colors, converting strings in tables to numbers, as well as converting between ra- dian and degrees (important when working with canvas or SVG). Chapter 5, Working with Arrays and Loops Arrays are the thing in this chapter, which provides a look at how to use arrays to create FIFO queues and LIFO stacks, as well as how to sort an array, work with multidimensional arrays, traverse arrays, use the new ECMAScript 5 array func- tionality to create filtered arrays, and validate array contents. The chapter also covers associative arrays, as well as various ways to traverse arrays. Chapter 6, Building Reusability with JavaScript Functions The JavaScript Function is the heart and soul of this language, and this chapter focuses on how to create functions, pass values to and from the function, create a recursive function, as well as build a dynamic function. The chapter also includes how to use Memoization and Currying, to enhance application efficiency and per- formance, as well as how to use an anonymous function in order to wrap global variables. Chapter 7, Handling Events Covers basic event handling tasks, including capturing events, canceling events, accessing the Event object, as well as working with both mouse and keyboard events. The chapter also covers the new HTML5 drag-and-drop functionality, as well as working with Safari’s Orientation Events (for mobile development). Chapter 8, Browser Pieces This chapter gets into the basic working components all browsers, and many other user agents, share. This includes creating new windows, changing a stylesheet, modifying an image, adding a bread crumb to a web page, bookmarking a dynamic page, as well as preserving the back button in Ajax applications. The chapter also introduces the new HTML5 History functionality for preserving dynamic state. Chapter 9, Form Elements and Validation This chapter continues the introduction of regular expressions from Chapter 2, but focuses on form elements and validation. The chapter also covers how to enable Preface | xvii
and disable form elements and hide or display elements, and includes how to modify a selection list, and canceling a form submission. Chapter 10, Debugging and Error Handling None of us like it, all of us need it: this chapter focuses on error handling in ap- plications, as well as how to use the different debugging tools in the book’s target browsers. Chapter 11, Accessing Page Elements This chapter covers the various ways you can access one or more document elements. Included are discussions on accessing all elements of a certain type, a specific element, or using the newer Selectors API to use CSS-like syntax to find elements. Also included is a discussion of namespace specifics, where appropriate. Chapter 12, Creating and Removing Elements and Attributes The chapter includes ways to create and add elements to a web document, includ- ing adding text, paragraphs, working with table elements, and moving and remov- ing document elements. The chapter also covers how to add and access element attributes, and includes coverage of namespace specifics, where appropriate. Chapter 13, Working with Web Page Spaces The web page is a canvas on which we create, and this chapter covers how to determine the area of the web page, the size of page elements, their location, as well as how to hide and show page sections. Popular behaviors such as expandos/ accordions and page overlays, as well as tabbed pages are included, as is how to create a collapsible sidebar and a hover-based pop-up message. Chapter 14, Creating Interactive and Accessible Effects with JavaScript, CSS, and ARIA For the longest time, our dynamic web page effects were literally silent to a signif- icant web community—those using screen readers. This chapter introduces the new Web Accessibility Initiative–Accessible Rich Internet Applications (WAI- ARIA) attributes and roles and demonstrates how they can make a web page come alive for all readers, not just those who are sighted. The chapter also covers other very common interactive effects, including providing a flash of color to signal an event, working with pop-up messages, creating Live Regions, and providing ac- cessible effects when validating forms. Chapter 15, Creating Media Rich and Interactive Applications I am not the most artistic of souls, but I do know how to make JavaScript work with the canvas element and SVG. In this chapter, I provide the basic steps needed in order to work with both of these media, as well as the newer WebGL 3D envi- ronment, and the new HTML5 video and audio elements. Chapter 16, JavaScript Objects Probably one of the most important chapters in the book, this chapter covers the basics of creating JavaScript objects, including how to keep data members private, adding Getters/Setters, using the new ECMAScript 5 object protection function- ality, chaining object methods, and using the new Prototype.bind. xviii | Preface
Chapter 17, JavaScript Libraries All of the book focuses on creating your own JavaScript objects and applications. This chapter introduces us to jQuery, one of the more popular JavaScript frame- work libraries. It covers common library tasks such as how to package your code into libraries, how to test the libraries, and how to build a jQuery plug-in, as well as how to use your library with other libraries, such as jQuery. Chapter 18, Communication Most of the chapter is focused on Ajax tasks, including preparing the data for sending, creating an XMLHttpRequest object, checking for errors, and processing the results. Also included are how to use a timer for a continuously updated query, how to create a dynamic image pop-up, and how to use JSON-P for cross-domain requests. The chapter introduces the postMessage functionality, for communicating between a remotely hosted widget and your own application. Chapter 19, Working with Structured Data Tasks covered include how to process an XML document returned from an Ajax call, using the new JSON object to parse JSON or stringify a JavaScript object. The chapter also includes how to work with Microformats or RDFa in the page. Chapter 20, Persistence This chapter covers how to create and use an HTTP cookie, of course, and how to store data using the page URL, but also provides recipes for working with the new sessionStorage and localStorage persistence techniques introduced with HTML5, and an introduction to client-side SQL databases. Chapter 21, JavaScript Outside the Box This chapter briefly gets into all the various ways that JavaScript can be used now, none of which have anything to do with traditional web page development. Inclu- ded are discussions on creating mobile and desktop widgets, mobile device appli- cation development, creating add-ons and extensions for browsers, as well as how JavaScript can be used with so many of our applications, such as OpenOffice (which I used to write this book) and Photoshop. I also include a discussion of desktop application development, including support for offline applications, and featuring examples of both the Web Workers API, and the File API. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Indicates computer code in a broad sense, including commands, arrays, elements, statements, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, Preface | xix
Comments 0
Loading comments...
Reply to Comment
Edit Comment