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

  • 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, including 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 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 document.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[


...

//--><!]]>
</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 examples. 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 substrings within strings.

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 working 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 radian 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 functionality 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 performance, 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 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 applications, 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, including adding text, paragraphs, working with table elements, and moving and removing 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 significant 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 accessible 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 environment, 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 functionality, chaining object methods, and using the new Prototype.bind.

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 framework 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. Included are discussions on creating mobile and desktop widgets, mobile device application 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, event handlers, XML tags, HTML tags, macros, the contents of files, and the output from commands.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Note

This icon signifies a tip, suggestion, or general note.

Warning

This icon indicates a warning or caution.

Websites and pages are mentioned in this book to help you locate online information that might be useful. Normally both the address (URL) and the name (title, heading) of a page are mentioned. Some addresses are relatively complicated, but you can probably locate the pages easier using your favorite search engine to find a page by its name, typically by writing it inside quotation marks. This may also help if the page cannot be found by its address; it may have moved elsewhere, but the name may still work.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “JavaScript Cookbook, by Shelley Powers. Copyright 2010 Shelley Powers, 9780596806132.”

If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at .

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

http://oreilly.com/catalog/9780596806132

To comment or ask technical questions about this book, send email to:

For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our website at:

http://oreilly.com

Safari® Books Online

Note

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 cell phone and mobile devices. Access new titles before they are 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.

O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com.

Acknowledgments

I want to thank Simon St.Laurent, who has been a long-time editor and friend, for all the help and encouragement he’s provided, in this book and in my previous books.

I also want to thank those who contributed time and expertise to review the book, and helped me do a better job: Elaine Nelson, Zachary Kessin, Chris Wells, and Sergey Ilinsky. My thanks also to Gez Lemon, who provided thoughtful commentary and help with my ARIA chapter, and Brad Neuberg for his help with SVGWeb in Chapter 15.

I also want to thank my copyeditors, and others in the production staff: Colleen Toporek, Adam Zaremba, Rob Romano, Kiel Van Horn, and Seth Maislin.

My gratitude, also, to those who helped create the specifications, such as HTML5 and ECMAScript 5, the tools, the APIs, the libraries, the browsers, and all the other fun stuff that helps make JavaScript development as exciting today as it was 15 years ago.

Get JavaScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.