O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

JavaScript Cookbook

Book Description

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.

  • Create interactive web and desktop applications
  • Work with JavaScript objects, such as String, Array, Number, and Math
  • Use JavaScript with Scalable Vector Graphics (SVG) and the canvas element
  • Store data in various ways, from the simple to the complex
  • Program the new HTML5 audio and video elements
  • Implement concurrent programming with Web Workers
  • Use and create jQuery plug-ins
  • Use ARIA and JavaScript to create fully accessible rich internet applications

Table of Contents

  1. A Note Regarding Supplemental Files
  2. Preface
    1. Audience, Assumptions, and Approach
    2. Conventions Used in This Book
    3. Using Code Examples
    4. How to Contact Us
    5. Safari® Books Online
    6. Acknowledgments
  3. 1. Working with JavaScript Strings
    1. 1.0. Introduction
    2. 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
    6. 1.5. Extracting a Substring from a String
    7. 1.6. Checking for an Existing, Nonempty String
    8. 1.7. Breaking a Keyword String into Separate Keywords
    9. 1.8. Inserting Special Characters
    10. 1.9. Processing Individual Lines of a textarea
    11. 1.10. Trimming Whitespace from the Ends of a String
    12. 1.11. Left- or Right-Pad a String
  4. 2. Using Regular Expressions
    1. 2.0. Introduction
    2. 2.1. Testing Whether a Substring Exists
    3. 2.2. Testing for Case-Insensitive Substring Matches
    4. 2.3. Validating a Social Security Number
    5. 2.4. Finding and Highlighting All Instances of a Pattern
    6. 2.5. Replacing Patterns with New Strings
    7. 2.6. Swap Words in a String Using Capturing Parentheses
    8. 2.7. Using Regular Expressions to Trim Whitespace
    9. 2.8. Replace HTML Tags with Named Entities
    10. 2.9. Searching for Special Characters
  5. 3. Dates, Time, and Timers
    1. 3.0. Introduction
    2. 3.1. Printing Out Today’s Date
    3. 3.2. Printing Out the UTC Date and Time
    4. 3.3. Printing Out an ISO 8601 Formatted Date
    5. 3.4. Converting an ISO 8601 Formatted Date to a Format Acceptable to the Date Object
    6. 3.5. Creating a Specific Date
    7. 3.6. Scheduling a Future Date
    8. 3.7. Tracking Elapsed Time
    9. 3.8. Creating a Timeout
    10. 3.9. Creating Recurring Timers
    11. 3.10. Using Function Closures with Timers
  6. 4. Working with Numbers and Math
    1. 4.0. Introduction
    2. 4.1. Keeping an Incremental Counter
    3. 4.2. Converting a Decimal to a Hexadecimal Value
    4. 4.3. Creating a Random Number Generator
    5. 4.4. Randomly Generating Colors
    6. 4.5. Converting Strings in a Table to Numbers
    7. 4.6. Summing All Numbers in a Table Column
    8. 4.7. Converting Between Degrees and Radians
    9. 4.8. Find the Radius and Center of a Circle to Fit Within a Page Element
    10. 4.9. Calculating the Length of a Circular Arc
  7. 5. Working with Arrays and Loops
    1. 5.0. Introduction
    2. 5.1. Looping Through an Array
    3. 5.2. Creating a Multidimensional Array
    4. 5.3. Creating a String from an Array
    5. 5.4. Sorting an Array
    6. 5.5. Store and Access Values in Order
    7. 5.6. Store and Access Values in Reverse Order
    8. 5.7. Create a New Array as a Subset of an Existing Array
    9. 5.8. Searching Through an Array
    10. 5.9. Flatten a Multidimensional Array
    11. 5.10. Search and Remove or Replace Array Elements
    12. 5.11. Applying a Function Against Each Array Element
    13. 5.12. Applying a Function to Every Element in an Array and Returning a New Array
    14. 5.13. Creating a Filtered Array
    15. 5.14. Validating Array Contents
    16. 5.15. Using an Associative Array to Store Form Element Names and Values
  8. 6. Building Reusability with JavaScript Functions
    1. 6.0. Introduction
    2. 6.1. Creating a Block of Reusable Code
    3. 6.2. Passing Single Data Values to and from a Function
    4. 6.3. Passing Complex Data Objects to a Function
    5. 6.4. Creating a Dynamic Runtime Function
    6. 6.5. Passing a Function As an Argument to Another Function
    7. 6.6. Implementing a Recursive Algorithm
    8. 6.7. Create a Function That Remembers Its State
    9. 6.8. Improving Application Performance with a Generalized Currying Function
    10. 6.9. Improve Application Performance with Memoization (Caching Calculations)
    11. 6.10. Using an Anonymous Function to Wrap Global Variables
  9. 7. Handling Events
    1. 7.0. Introduction
    2. 7.1. Detecting When the Page Has Finished Loading
    3. 7.2. Capturing the Location of a Mouse Click Event Using the Event Object
    4. 7.3. Creating a Generic, Reusable Event Handler Function
    5. 7.4. Canceling an Event Based on Changed Circumstance
    6. 7.5. Preventing an Event from Propagating Through a Set of Nested Elements
    7. 7.6. Capturing Keyboard Activity
    8. 7.7. Using the New HTML5 Drag-and-Drop
    9. 7.8. Using Safari Orientation Events and Other Mobile Development Environments
  10. 8. Browser Pieces
    1. 8.0. Introduction
    2. 8.1. Ask the Web Page Reader to Confirm an Action
    3. 8.2. Creating a New, Stripped-Down Browser Window
    4. 8.3. Finding Out About the Browser Accessing the Page
    5. 8.4. Warning the Web Page Reader About Leaving a Page
    6. 8.5. Changing Stylesheets Depending on Color Support
    7. 8.6. Modifying Image Dimensions Depending on Page Size
    8. 8.7. Creating Breadcrumbs in a CMS Template Page
    9. 8.8. Bookmarking a Dynamic Page
    10. 8.9. Preserving State for Back Button, Page Refresh
  11. 9. Form Elements and Validation
    1. 9.0. Introduction
    2. 9.1. Accessing Form Text Input Values
    3. 9.2. Dynamically Disabling and Enabling Form Elements
    4. 9.3. Getting Information from a Form Element Based on an Event
    5. 9.4. Performing an Action When a Radio Button Is Clicked
    6. 9.5. Checking for a Valid Phone Number
    7. 9.6. Canceling a Form Submission
    8. 9.7. Preventing Duplicate Form Submissions
    9. 9.8. Hiding and Displaying Form Elements
    10. 9.9. Modifying a Selection List Based on Other Form Decisions
  12. 10. Debugging and Error Handling
    1. 10.0. Introduction
    2. 10.1. Gracefully Handling No JavaScript Support
    3. 10.2. Checking for Errors in Functions
    4. 10.3. Using an Alert for Simple Debugging
    5. 10.4. Catching an Error and Providing Graceful Error Handling
    6. 10.5. Initiating Manageable Errors
    7. 10.6. Using Firebug with Firefox
    8. 10.7. Setting a Breakpoint and Examining Data with Firebug
    9. 10.8. Firefox and the Console
    10. 10.9. Using IE’s Built-in Debugger
    11. 10.10. Setting a Breakpoint with IE Developer Tools
    12. 10.11. Opera’s Dragonfly
    13. 10.12. Setting a Breakpoint with Dragonfly
    14. 10.13. Turning on Safari’s Development Tools
    15. 10.14. Setting a Breakpoint with Safari’s Debugger
    16. 10.15. Debugging in Chrome
  13. 11. Accessing Page Elements
    1. 11.0. Introduction
    2. 11.1. Access a Given Element and Find Its Parent and Child Elements
    3. 11.2. Accessing All Images in the Web Page
    4. 11.3. Discover All Images Within an Article
    5. 11.4. Discover all Images in Articles Using the Selectors API
    6. 11.5. Finding the Parent Element for a Group of Elements
    7. 11.6. Highlighting the First Paragraph in Every Element
    8. 11.7. Apply a Striping Theme to an Unordered List
    9. 11.8. Creating an Array of All Elements of a Given Class
    10. 11.9. Finding All Elements That Share an Attribute
    11. 11.10. Finding All Checked Options
    12. 11.11. Summing All the Values in a Table Row
    13. 11.12. Get Element Attributes
    14. 11.13. Get Style Information for an Element
  14. 12. Creating and Removing Elements and Attributes
    1. 12.0. Introduction
    2. 12.1. Using innerHTML: A Quick and Easy Approach to Adding Content
    3. 12.2. Inserting Elements Before Existing Page Elements
    4. 12.3. Appending a New Element to the End of a Page
    5. 12.4. Triggering Older Versions of IE to Style New Elements
    6. 12.5. Inserting a New Paragraph
    7. 12.6. Adding Text to a New Paragraph
    8. 12.7. Adding Attributes to an Existing Element
    9. 12.8. Testing for a Boolean Attribute
    10. 12.9. Removing an Attribute
    11. 12.10. Moving a Paragraph
    12. 12.11. Replacing Links with Footnote Bullets
    13. 12.12. Adding Rows to an Existing Table
    14. 12.13. Removing a Paragraph from a div Element
    15. 12.14. Deleting Rows from an HTML Table
    16. 12.15. Changing the Element’s CSS Style Properties
  15. 13. Working with Web Page Spaces
    1. 13.0. Introduction
    2. 13.1. Determining the Area of the Web Page
    3. 13.2. Measuring Elements
    4. 13.3. Locating Elements in the Page
    5. 13.4. Hiding Page Sections
    6. 13.5. Creating Collapsible Form Sections
    7. 13.6. Adding a Page Overlay
    8. 13.7. Creating Tab Pages
    9. 13.8. Creating Hover-Based Pop-up Info Windows
    10. 13.9. Collapsing or Resizing the Sidebar
  16. 14. Creating Interactive and Accessible Effects with JavaScript, CSS, and ARIA
    1. 14.0. Introduction
    2. 14.1. Displaying a Hidden Page Section
    3. 14.2. Creating an Alert Message
    4. 14.3. Highlighting Form Field with Missing or Incorrect Data
    5. 14.4. Adding Keyboard Accessibility to a Page Overlay
    6. 14.5. Creating Collapsible Form Sections
    7. 14.6. Displaying a Flash of Color to Signal an Action
    8. 14.7. Adding ARIA Attributes to a Tabbed Page Application
    9. 14.8. Live Region
  17. 15. Creating Media Rich and Interactive Applications
    1. 15.0. Introduction
    2. 15.1. Creating Basic Shapes in Canvas (Using the canvas Element)
    3. 15.2. Implementing Canvas Applications in IE
    4. 15.3. Creating a Dynamic Line Chart in Canvas
    5. 15.4. Adding JavaScript to an SVG File
    6. 15.5. Accessing SVG from Web Page Script
    7. 15.6. Emulating SVG in Internet Explorer
    8. 15.7. Enable Interactive SVG Embedded in HTML
    9. 15.8. Using the Math Functions to Create a Realistic, Ticking Analog Clock in SVG
    10. 15.9. Integrating SVG and the Canvas Element in HTML
    11. 15.10. Turning on WebGL Support in Firefox and WebKit/Safari
    12. 15.11. Running a Routine When an Audio File Begins Playing
    13. 15.12. Controlling Video from JavaScript with the video Element
  18. 16. JavaScript Objects
    1. 16.0. Introduction
    2. 16.1. Defining a Basic JavaScript Object
    3. 16.2. Keeping Object Members Private
    4. 16.3. Expanding Objects with prototype
    5. 16.4. Adding Getter/Setter to Objects
    6. 16.5. Inheriting an Object’s Functionality
    7. 16.6. Extending an Object by Defining a New Property
    8. 16.7. Enumerating an Object’s Properties
    9. 16.8. Preventing Object Extensibility
    10. 16.9. Preventing Object Additions and Changes to Property Descriptors
    11. 16.10. Preventing Any Changes to an Object
    12. 16.11. One-Off Objects and Namespacing Your JavaScript
    13. 16.12. Rediscovering “this” with Prototype.bind
    14. 16.13. Chaining Your Object’s Methods
  19. 17. JavaScript Libraries
    1. 17.0. Introduction
    2. 17.1. Packaging Your Code
    3. 17.2. Testing Your Code with JsUnit
    4. 17.3. Minify Your Library
    5. 17.4. Hosting Your Library
    6. 17.5. Using an External Library: Building on the jQuery Framework
    7. 17.6. Using Existing jQuery Plug-ins
    8. 17.7. Convert Your Library to a jQuery Plug-in
    9. 17.8. Safely Combining Several Libraries in Your Applications
  20. 18. Communication
    1. 18.0. Introduction
    2. 18.1. Accessing the XMLHttpRequest Object
    3. 18.2. Preparing the Data for Transmission
    4. 18.3. Determining the Type of Query Call
    5. 18.4. Adding a Callback Function to an Ajax Request
    6. 18.5. Checking for an Error Condition
    7. 18.6. Processing a Text Result
    8. 18.7. Making an Ajax Request to Another Domain (Using JSONP)
    9. 18.8. Populating a Selection List from the Server
    10. 18.9. Using a Timer to Automatically Update the Page with Fresh Data
    11. 18.10. Communicating Across Windows with PostMessage
  21. 19. Working with Structured Data
    1. 19.0. Introduction
    2. 19.1. Process an XML Document Returned from an Ajax Call
    3. 19.2. Extracting Pertinent Information from an XML Tree
    4. 19.3. Generate a JavaScript Object with JSON, Old-School Style
    5. 19.4. Parse a JSON Formatted String
    6. 19.5. Convert an Object to a Filtered/Transformed String with JSON
    7. 19.6. Convert hCalendar Microformat Annotations into a Canvas Timeline
    8. 19.7. Glean Page RDFa and Convert It into JSON Using rdfQuery and the jQuery RDF Plug-in
  22. 20. Persistence
    1. 20.0. Introduction
    2. 20.1. Attaching Persistent Information to URLs
    3. 20.2. Creating a Cookie to Persist Information Across Pages
    4. 20.3. Persisting Information Using the History.pushState Method and window.onpopevent
    5. 20.4. Using sessionStorage for Client-Side Storage
    6. 20.5. Creating a localStorage Client-Side Data Storage Item
    7. 20.6. Persisting Data Using a Relational Data Store
  23. 21. JavaScript Outside the Box
    1. 21.0. Introduction
    2. 21.1. Creating a Browser Add-0n, Plug-in, or Extension
    3. 21.2. Creating Desktop and Mobile Widgets
    4. 21.3. Creating JavaScript Applications for the iPhone, Android, and BlackBerry with PhoneGap
    5. 21.4. Enhancing Tools with JavaScript
    6. 21.5. Creating Efficient Desktop Applications with Web Workers and the File API
  24. Index
  25. About the Author
  26. Colophon
  27. Copyright