You are previewing JavaScript Cookbook, 2nd Edition.
O'Reilly logo
JavaScript Cookbook, 2nd Edition

Book Description

Problem solving with JavaScript is a lot trickier now that its use has expanded considerably in size, scope, and complexity. This cookbook has your back, with recipes for common tasks across the JavaScript world, whether you’re working in the browser, the server, or a mobile environment. Each recipe includes reusable code and practical advice for tackling JavaScript objects, Node, Ajax, JSON, data persistence, graphical and media applications, complex frameworks, modular JavaScript, APIs, and many related technologies.

Table of Contents

  1. The World of JavaScript
    1. Book Audience
    2. Book Architecture or Why Is This Book Organized in This Way?
    3. Conventions Used in This Book
    4. Using Code Examples
    5. Safari® Books Online
    6. How to Contact Us
    7. Acknowledgments
  2. I. Classic JavaScript
    1. 1. The JavaScript Not-So-Simple Building Blocks
      1. Differentiating Between a JavaScript Object, Primitive, and Literal
      2. Extracting a List from a String
      3. Checking for an Existing, Nonempty String
      4. Inserting Special Characters
      5. Replacing Patterns with New Strings
      6. Finding and Highlighting All Instances of a Pattern
      7. Swapping Words in a String Using Capturing Parentheses
      8. Replacing HTML Tags with Named Entities
      9. Converting an ISO 8601 Formatted Date to a Date Object Acceptable Format
      10. Using Function Closures with Timers
      11. Tracking Elapsed Time
      12. Converting a Decimal to a Hexadecimal Value
      13. Summing All Numbers in a Table Column
      14. Converting Between Degrees and Radians
      15. Find the Radius and Center of a Circle to Fit Within a Page Element
      16. Calculating the Length of a Circular Arc
      17. Using ES6 String Extras Without Leaving Users in the Dirt
    2. 2. JavaScript Arrays
      1. Searching Through an Array
      2. Flattening a Two-Dimensional Array with concat() and apply()
      3. Removing or Replacing Array Elements
      4. Extracting a Portion of an Array
      5. Applying a Function Against Each Array Element
      6. Traversing the Results from querySelectorAll() with forEach() and call()
      7. Applying a Function to Every Element in an Array and Returning a New Array
      8. Creating a Filtered Array
      9. Validating Array Contents
      10. Using an Associative Array to Store Form Element Names and Values
      11. Using a Destructuring Assignment to Simplify Code
    3. 3. Functions: The JavaScript Building Blocks
      1. Placing Your Function and Hoisting
      2. Passing a Function As an Argument to Another Function
      3. Implementing a Recursive Algorithm
      4. Preventing Code Blocking with a Timer and a Callback
      5. Creating a Function That Remembers Its State
      6. Converting Function Arguments into an Array
      7. Reducing Redundancy by Using a Partial Application
      8. Improving Application Performance with Memoization (Caching Calculations)
      9. Using an Anonymous Function to Wrap Global Variables
      10. Providing a Default Parameter
    4. 4. The Malleable JavaScript Object
      1. Keeping Object Members Private
      2. Using Prototype to Create Objects
      3. Inheriting an Object’s Functionality
      4. Extending an Object by Defining a New Property
      5. Preventing Object Extensibility
      6. Preventing Any Changes to an Object
      7. Namespacing Your JavaScript Objects
      8. Rediscovering this with Prototype.bind
      9. Chaining Your Object’s Methods
    5. 5. JavaScript and Directly Accessing the User Interface
      1. Accessing a Given Element and Finding Its Parent and Child Elements
      2. Accessing All Images in the Web Page
      3. Discovering All Images in Articles Using the Selectors API
      4. Setting an Element’s Style Attribute
      5. Applying a Striped Theme to an Unordered List
      6. Finding All Elements That Share an Attribute
      7. Inserting a New Paragraph
      8. Adding Text to a New Paragraph
      9. Deleting Rows from an HTML Table
      10. Adding a Page Overlay
      11. Creating Collapsible Form Sections
      12. Hiding Page Sections
      13. Creating Hover-Based Pop-Up Info Windows
      14. Displaying a Flash of Color to Signal an Action
    6. 6. Preliminary Testing and Accessibility
      1. Cleaning Up Your Code with JSHint
      2. Unit Testing Your Code with QUnit
      3. Testing Your Application in Various Environments
      4. Performance Testing Different Coding Techniques
      5. Highlighting Errors Accessibly
      6. Creating an Accessible Automatically Updated Region
    7. 7. Creating and Using JavaScript Libraries
      1. Finding the Perfect Library
      2. Testing for Features with Modernizr.load
      3. Going Beyond the Math Object’s Capability
      4. Finding the Number of Days Between Two Dates
      5. Using an External Library: Building on the jQuery Framework
      6. Using a jQuery Plugin
      7. Handling Keyboard Shortcuts with Mousetrap
      8. Utilizing the Utility Library Underscore
      9. Packaging Your Code
      10. Adding Support for Private Data Members
      11. Minify Your Library
      12. Hosting Your Library
      13. Serving Code from a CDN
      14. Convert Your Library to a jQuery Plug-in
      15. Safely Combining Several Libraries in Your Applications
    8. 8. Simplified Client-Server Communication and Data
      1. Handling an XML Document Returned via an Ajax Call
      2. Extracting Pertinent Information from an XML Tree
      3. Parsing and Automatically Modifying JSON
      4. Converting an Object to a Filtered/Transformed String with JSON
      5. Making an Ajax Request to Another Domain (Using JSONP)
      6. Processing JSON from an Ajax Request
      7. Populating a Selection List from the Server
      8. Using a Timer to Automatically Update the Page with Fresh Data
    9. 9. Creating Media Rich, Interactive Web Effects
      1. Creating a Dynamic Line Chart in Canvas
      2. Adding JavaScript to SVG
      3. Accessing SVG from Web Page Script
      4. Integrating SVG and the Canvas Element in HTML
      5. Running a Routine When an Audio File Begins Playing
      6. Controlling Video from JavaScript with the video Element
      7. Adding Filter Effects to Video via Canvas
  3. II. JavaScript, All Blown Up
    1. 10. The New ECMAScript Standard Objects
      1. Using let in Your Browser Application
      2. Creating a Collection of Non-Duplicated Values
      3. Creating Unique Key/Value Pairs with Uniquely Different Keys
      4. Creating Absolutely Unique Object Property Keys
      5. Iterating Through Tasks Made Easy
      6. Creating Functions that Gracefully Yield
      7. Implementing Just-in-Time Object Behavioral Modifications with Proxies
      8. Creating a True Class and Extending It (with a Little Help from Traceur)
      9. Using Promises for Efficient Asynchronous Processing
    2. 11. Node: JavaScript on the Server
      1. Responding to a Simple Browser Request
      2. Serving Up Formatted Data
      3. Reading and Writing File Data
      4. Using let and Other ES 6 Additions in Node
      5. Interactively Trying Out Node Code Snippets with REPL
      6. Getting Input from the Terminal
      7. Working with Node Timers and Understanding the Node Event Loop
      8. Managing Callback Hell
      9. Accessing Command-Line Functionality Within a Node Application
      10. Running Node and Apache on the Same Port
      11. Keeping a Node Instance Up and Running
      12. Monitoring Application Changes and Restarting
      13. Screen Scraping with Request
      14. Creating a Command-Line Utility with Help From Commander
    3. 12. Modularizing and Managing JavaScript
      1. Loading Scripts with a Script Loader
      2. Loading Scripts Asynchronously the HTML5 Way
      3. Converting Your JavaScript to AMD and RequireJS
      4. Using RequireJS with jQuery or Another Library
      5. Loading and Using Dojo Modules
      6. Installing and Maintaining Node Modules with npm
      7. Searching for a Specific Node Module via npm
      8. Converting Your Library into a Node Module
      9. Taking Your Code Across All Module Environments
      10. Creating an Installable Node Module
      11. Packaging and Managing Your Client-Side Dependencies with Bower
      12. Compiling Node.js Modules for Use in the Browser with Browserify
      13. Unit Testing Your Node Modules
      14. Running Tasks with Grunt
    4. 13. Fun with APIs
      1. Accessing JSON-Formatted Data via a RESTful API
      2. Creating a RESTFul API with Restify
      3. Enabling a Mobile-Like Notification in the Desktop Browser
      4. Loading a File Locally in the Browser
      5. Creating a Mini E-Pub Reader Using Web Workers and the File API
      6. Exploring Google Maps and Other APIS
      7. Accessing Twitter’s API from a Node Application
    5. 14. JavaScript Frameworks
      1. Using the Express-Generator to Generate an Express Site
      2. Converting a Generated Express Site into a Basic MVC App
      3. Choosing a SPA Framework: Deconstructing the TodoMVC
      4. Working with the OAuth Framework
      5. Extending the Possible with Web Components
    6. 15. Advanced Client-Server Communications and Streams
      1. Allowing Cross-Domain Requests
      2. Implementing a PUT Request in Ajax
      3. Sending Binary Data Through Ajax and Loading into an Image
      4. Sharing HTTP Cookies Across Domains
      5. Establishing Two-Way Communication Between Client and Server
      6. Unloading and Zipping Files Using Transform Streams
      7. Testing the Performance and Capability of Your WebSockets Application
    7. 16. Data Visualizations and Client/Server Graphics
      1. Creating an SVG Bar Chart with D3
      2. Mapping Data Point Variations with a Radar Chart
      3. Feeding a Scrolling Timeline via WebSocket
      4. Generating Screenshots of Generated Web Page Content (PhantomJS)
      5. Converting Graphics to Text (Ocrad.js)
      6. Cropping (or Otherwise Modifying) Uploaded Images
    8. 17. Data and Persistence
      1. Validating Form Data
      2. Persisting Information Using HTML5
      3. Using sessionStorage for Client-Side Storage
      4. Creating a localStorage Client-Side Data Storage Item
      5. Using Squel.js to Query a MySQL Database
      6. Persisting Larger Chunks of Data on the Client Using IndexedDB
      7. Accessing Data in the Cloud Using Dropbox Datastores
    9. 18. JavaScript Hits the (Mobile) Road
      1. Creating an Installable, Hosted Web App
      2. Packaging Web Apps for the Amazon Appstore
      3. Building a Basic Android App Using Cordova (PhoneGap)
      4. Porting Where Am I? to Android
      5. Creating a Geolocation Firefox OS App
      6. Porting the Geolocation App to a Google Chrome App
      7. Publishing Your Geolocation App in the Kindle Fire OS Environment
      8. Debugging Your Android or Amazon Fire OS App
      9. Getting Information About the Device
    10. A. Up and Running in jsBin and jsFiddle
      1. The Console Is Your Friend
      2. jsBin and jsFiddle: Online JavaScript Playgrounds
  4. Index
  5. Colophon
  6. Copyright