JavaScript Cookbook

Why reinvent the wheel every time you run into a problem with JavaScript? This cookbook
is chock-full of code recipes that address common programming tasks, as well as
techniques for building web apps that work in any browser. Just copy and paste the code
samples into your project - you'll get the job done faster and learn more about
JavaScript in the process.

You'll also learn how to take advantage of the latest features in ECMAScript 5 and HTML5,
including the new cross-domain widget communication technique, HTML5's video and audio
elements, and the drawing canvas. You'll find recipes for using these features with
JavaScript to build high-quality application interfaces.

Contents:

1. Working with JavaSript Strings

Concatenating Two or More Strings
Concatenating a Sting and Another Data Type
Conditionally Comparing Strings
Finding a Substring in a String
Extracting a Substring from a String
Checking for an Existing, Nonempty String
Breaking a Keyword String into Separate Keywords
Inserting Special Characters
Processing Individual Lines of a textarea
Trimming Whitespace from the Ends of a String
Left or Right Pad a String

2. Using Regular Expressions

Testing Whether a Substring Exists
Testing for Case-Insensitive Substring Matches
Validating a Social Security Number
Finding and Highlighting All Instances of a Pattern
Replacing Patterns with New Strings
Swap Words in a String Using capturing Parentheses
Using Regular Expressions to Trim Whitespace
Replace HTML Tags with Named Entities
Searching for Special Characters

3. Dates, Time, and Timers

Printing Out Today's Date
Printing Out the UTC date and Time
Printing Out an ISO 8601 Formatted Date
Converting an ISO 8601 Formatted Date to a Format Acceptable to the Date Object
Creating a Specific Date
Scheduling a Future Date
Tracking Elapsed Time
Creating a Timeout
Creating Recurring Timers
Using Function Closures with Timers

4. Working with Numbers and Math

Keeping an Incremental Counter
Converting a Decimal to a Hexadecimal Value
Creating a Random Number Generator
Randomly Generating Colors
Converting Strings in a Table to Numbers
Summing All Numbers in a Table Column
Converting Between Degrees and Radians
Find the Radius and Center of a Circle to Fit Within a Page Element
Calculating the Length of a Circular Arc

5. Working with Arrays and Loops

Looping Through an Array
Creating a Multidimensional Array
Creating a String from an Array
Sorting an Array
Store and Access Values in Order
Store and Access Values in Reverse Order
Create a New Array as a Subset of an Existing Array
Searching Through an Array
Flatten a Multidimensional Array
Search and Remove or Replace Array Elements
Applying a Function Against Each Array Element
Applying a Function to Every Element in an Array and Returning a New Array
Creating a Filtered Array
Validating Array Contents
Using Associative Array to Store Form Element Names and Values

6. Building Reusability with JavaScript Functions

Creating a Block of Reusable Code
Passing Single Data Values to and From a Function
Passing Complex Data Objects to a Function
Creating a Dynamic Runtime Function
Passing a Function as an Argument to Another Function
Implementing a Recursive Algorithm
Create a Function that Remembers Its State
Improving Application Performance with a Generalized Currying Function
Improve Application Performance with Memorization (Cashing Calculations)
Using an Anonymous Function to Wrap Global Variables

7. Handling Events

Detecting When the Page Has Finished Loading
Capturing the Location of a Mouse Click Event Using the Event Object
Creating a Generic, Reusable Event Handler Function
Canceling an Event Based on Changed Circumstance
Preventing an Event from Propagating Through a Set of Nested Elements
Capturing Keyboard Activity
Using the New HTML5 Drag-and-Drop
Using Safari Orientation Events and Other Mobile Development Environments

8. Browser Pieces

Ask the Web Page Reader to Confirm an Action
Creating a New, Stripped-Down Browser Window
Finding Out About the Browser Accessing the Page
Warning the Web Page Reader About Leaving a Page
Changing Stylesheets Depending on Color Support
Modifying Image Dimensions Depending on Page Size
Creating Breadcrumbs in a CMS Template Page
Bookmarking a Dynamic Page
Preserving State for Back Button, Page Refresh

9. Form Elements and Validation

Accessing Form Text Input Values
Dynamically Disabling and Enabling Form Elements
Getting Information from Form Elements Based on an Event
Performing an Action When a Radio Button is Clicked
Checking for a Valid Phone Number
Canceling a Form Submission
Preventing Duplicate Form Submissions
Hiding and Displaying Form Elements

10. Debugging and Error Handling

Gracefully Handling No JavaScript Support
Checking for Errors in Functions
Using an Alert for Simple Debugging
Catching an Error and Providing Graceful Error Handling
Initiating Manageable Errors
Using Firebug with Firefox
Setting a Breakpoint and Examining Data with Firebug
Firefox and the Console
Using IE's Built-in Debugger
Setting a Breakpoint with IE Developer Tools
Opera's Dragonfly
Setting a Breakpoint with Dragonfly
Turning on Safari's Development Tools
Setting a Breakpoint with Safari's Debugger
Debugging Chrome

11. Accessing Page Elements

Access a Given Element and Find Its Parent and Child Elements
Accessing All Images in the Web Page
Discover All Images Within an Article
Discover all Images in Articles Using the Selectors API
Finding the Parent Element for a Group of Elements
Highlighting the First Paragraph in Every Element
Applying a Striping Theme to an Unordered List
Creating an Array of All Elements of a Given Class
Finding All Elements That Share an Attribute
Finding All Checked Options
Summing All the Values in a Table Row
Get Elements Attributes
Get Style Information for an Element

12. Creating and Removing Elements and Attributes

Using innerHTML: A Quick and Easy Approach to Adding Content
Inserting Elements Before Existing Page Elements
Appending a New Element to the End of a Page
Triggering Older Versions of IE to Style New Elements
Inserting a New Paragraph
Adding Text to a New Paragraph
Adding Attributes to an Existing Element
Testing for a Boolean Attribute
Removing an Attribute
Moving a Paragraph
Replacing Links with Footnote Bullets
Adding Rows to an Existing Table
Removing a Paragraph from a div Element
Deleting Rows From an HTML Table
Changing the Element's CSS Style Properties

Displaying a Hidden Page Section
Creating an Alert Message
Highlighting Form Field with Missing or Incorrect Data
Adding Keyboard Accessibility to a Page Overlay
Creating Collapsible Form Sections
Displaying a Flash of Color to Signal an Action
Adding ARIA Attributes to a Tabbed Page Application
Live Region

15. Creating Media Rich and Interactive Applications

Creating Basic Shapes in Canvas (Using the canvas Element)
Implementing Canvas Applications in IE
Creating a Dynamic Line Chart in Canvas
Adding JavaScript to an SVG File
Accessing SVG from Web Page Script
Emulating SVG in Internet Explorer
Enable Interactive SVG Embedded in HTML
Using the Math Functions to Create a Realistic, Ticking Analog Clock in SVG
Integrating SVG and the Canvas Element in HTML
Turning on WebGL Support in Firefox and WebKit/Safari
Running Routine When an Audio File Begins Playing

Accessing the XMLHttpRequest Object
Preparing the Data for Transmission
Determining the Type of Query Call
Adding a Callback Function to an Ajax Request
Checking for an Error Condition
Processing a Text Result
Making an Ajax Request to Another Domain (Using JSONP)
Populating a Selection List from the Server
Using a Timer to Automatically Update the Page with Fresh Data
Communicating Across Windows with PostMessage

19. Working with Structured Data

Process an XML Document Returned from an Ajax Call
Extracting Pertinent Information from an XML Tree
Generate a JavaScript Object with JSON, Old-School Style
Parse a JSON Formatted String
Convert an Object to a Filtered/Transformed String with JSON
Convert hCalendar Microformat Annotations into a Canvas Timeline
Glean Page RDFs and Convert It into JSON Using rdfQuery and the jQuery RDF Plug-in

20. Persistence

Attaching Persistent Information to URLs
Creating a Cookie to Persist Information Across Pages
Persisting Information Using the Hoistory.pushState Method and window.onpopevent
Using sessionStorgae for Client-Side Storage
Creating a localStorage Client-Side Data Storage Item
Persisting Data Using a Relational Data Store

Reader Brett Merkey says,"One bit of advice if you are like me when you get a reference
collection of this sort: I immediately flip through the table of contents or the index to
get to whatever topic I am currently obsessing on.

"In the case of this book, you may want to spend a few minutes in the oft-ignored
preface. It contains some noteworthy information on the author's approach. Specifically:
"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."

"The author is a bit more forgiving in the case of IE7: "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."

"I work on teams developing browser-based applications for the real world, so IE6 is
still absolutely relevant to me. In fact, the corporation for which I honestly sweat is
itself "standardized" on IE6 for all employees. Even so, I still recommend this book
because of the relevancy of the examples and its forward-looking approach.

The fact that the code download file is about 63 megs compressed should give an idea
of how much is contained in this big store of scripting knowledge."