You are previewing jQuery Cookbook.

jQuery Cookbook

Cover of jQuery Cookbook by Cody Lindley Published by O'Reilly Media, Inc.
  1. jQuery Cookbook
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Foreword
    4. Contributors
      1. Chapter Authors
      2. Tech Editors
    5. Preface
      1. Who This Book Is For
      2. What You’ll Learn
      3. jQuery Style and Conventions
      4. Other Options
      5. If You Have Problems Making Examples Work
      6. If You Like (or Don’t Like) This Book
      7. Conventions Used in This Book
      8. Using Code Examples
      9. Safari® Books Online
      10. How to Contact Us
    6. 1. jQuery Basics
      1. Introduction
      2. 1.1. Including the jQuery Library Code in an HTML Page
      3. 1.2. Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load
      4. 1.3. Selecting DOM Elements Using Selectors and the jQuery Function
      5. 1.4. Selecting DOM Elements Within a Specified Context
      6. 1.5. Filtering a Wrapper Set of DOM Elements
      7. 1.6. Finding Descendant Elements Within the Currently Selected Wrapper Set
      8. 1.7. Returning to the Prior Selection Before a Destructive Change
      9. 1.8. Including the Previous Selection with the Current Selection
      10. 1.9. Traversing the DOM Based on Your Current Context to Acquire a New Set of DOM Elements
      11. 1.10. Creating, Operating on, and Inserting DOM Elements
      12. 1.11. Removing DOM Elements
      13. 1.12. Replacing DOM Elements
      14. 1.13. Cloning DOM Elements
      15. 1.14. Getting, Setting, and Removing DOM Element Attributes
      16. 1.15. Getting and Setting HTML Content
      17. 1.16. Getting and Setting Text Content
      18. 1.17. Using the $ Alias Without Creating Global Conflicts
    7. 2. Selecting Elements with jQuery
      1. Introduction
      2. 2.1. Selecting Child Elements Only
      3. 2.2. Selecting Specific Siblings
      4. 2.3. Selecting Elements by Index Order
      5. 2.4. Selecting Elements That Are Currently Animating
      6. 2.5. Selecting Elements Based on What They Contain
      7. 2.6. Selecting Elements by What They Don’t Match
      8. 2.7. Selecting Elements Based on Their Visibility
      9. 2.8. Selecting Elements Based on Attributes
      10. 2.9. Selecting Form Elements by Type
      11. 2.10. Selecting an Element with Specific Characteristics
      12. 2.11. Using the Context Parameter
      13. 2.12. Creating a Custom Filter Selector
    8. 3. Beyond the Basics
      1. Introduction
      2. 3.1. Looping Through a Set of Selected Results
      3. 3.2. Reducing the Selection Set to a Specified Item
      4. 3.3. Convert a Selected jQuery Object into a Raw DOM Object
      5. 3.4. Getting the Index of an Item in a Selection
      6. 3.5. Making a Unique Array of Values from an Existing Array
      7. 3.6. Performing an Action on a Subset of the Selected Set
      8. 3.7. Configuring jQuery Not to Conflict with Other Libraries
      9. 3.8. Adding Functionality with Plugins
      10. 3.9. Determining the Exact Query That Was Used
    9. 4. jQuery Utilities
      1. Introduction
      2. 4.1. Detecting Features with
      3. 4.2. Iterating Over Arrays and Objects with jQuery.each
      4. 4.3. Filtering Arrays with jQuery.grep
      5. 4.4. Iterating and Modifying Array Entries with
      6. 4.5. Combining Two Arrays with jQuery.merge
      7. 4.6. Filtering Out Duplicate Array Entries with jQuery.unique
      8. 4.7. Testing Callback Functions with jQuery.isFunction
      9. 4.8. Removing Whitespace from Strings or Form Values with jQuery.trim
      10. 4.9. Attaching Objects and Data to DOM with
      11. 4.10. Extending Objects with jQuery.extend
    10. 5. Faster, Simpler, More Fun
      1. Introduction
      2. 5.1. That’s Not jQuery, It’s JavaScript!
      3. 5.2. What’s Wrong with $(this)?
      4. 5.3. Removing Redundant Repetition
      5. 5.4. Formatting Your jQuery Chains
      6. 5.5. Borrowing Code from Other Libraries
      7. 5.6. Writing a Custom Iterator
      8. 5.7. Toggling an Attribute
      9. 5.8. Finding the Bottlenecks
      10. 5.9. Caching Your jQuery Objects
      11. 5.10. Writing Faster Selectors
      12. 5.11. Loading Tables Faster
      13. 5.12. Coding Bare-Metal Loops
      14. 5.13. Reducing Name Lookups
      15. 5.14. Updating the DOM Faster with .innerHTML
      16. 5.15. Debugging? Break Those Chains
      17. 5.16. Is It a jQuery Bug?
      18. 5.17. Tracing into jQuery
      19. 5.18. Making Fewer Server Requests
      20. 5.19. Writing Unobtrusive JavaScript
      21. 5.20. Using jQuery for Progressive Enhancement
      22. 5.21. Making Your Pages Accessible
    11. 6. Dimensions
      1. Introduction
      2. 6.1. Finding the Dimensions of the Window and Document
      3. 6.2. Finding the Dimensions of an Element
      4. 6.3. Finding the Offset of an Element
      5. 6.4. Scrolling an Element into View
      6. 6.5. Determining Whether an Element Is Within the Viewport
      7. 6.6. Centering an Element Within the Viewport
      8. 6.7. Absolutely Positioning an Element at Its Current Position
      9. 6.8. Positioning an Element Relative to Another Element
      10. 6.9. Switching Stylesheets Based on Browser Width
    12. 7. Effects
      1. Introduction
      2. 7.1. Sliding and Fading Elements in and out of View
      3. 7.2. Making Elements Visible by Sliding Them Up
      4. 7.3. Creating a Horizontal Accordion
      5. 7.4. Simultaneously Sliding and Fading Elements
      6. 7.5. Applying Sequential Effects
      7. 7.6. Determining Whether Elements Are Currently Being Animated
      8. 7.7. Stopping and Resetting Animations
      9. 7.8. Using Custom Easing Methods for Effects
      10. 7.9. Disabling All Effects
      11. 7.10. Using jQuery UI for Advanced Effects
    13. 8. Events
      1. Introduction
      2. 8.1. Attaching a Handler to Many Events
      3. 8.2. Reusing a Handler Function with Different Data
      4. 8.3. Removing a Whole Set of Event Handlers
      5. 8.4. Triggering Specific Event Handlers
      6. 8.5. Passing Dynamic Data to Event Handlers
      7. 8.6. Accessing an Element ASAP (Before document.ready)
      8. 8.7. Stopping the Handler Execution Loop
      9. 8.8. Getting the Correct Element When Using
      10. 8.9. Avoid Multiple hover() Animations in Parallel
      11. 8.10. Making Event Handlers Work for Newly Added Elements
    14. 9. Advanced Events
      1. Introduction
      2. 9.1. Getting jQuery to Work When Loaded Dynamically
      3. 9.2. Speeding Up Global Event Triggering
      4. 9.3. Creating Your Own Events
      5. 9.4. Letting Event Handlers Provide Needed Data
      6. 9.5. Creating Event-Driven Plugins
      7. 9.6. Getting Notified When jQuery Methods Are Called
      8. 9.7. Using Objects’ Methods as Event Listeners
    15. 10. HTML Form Enhancements from Scratch
      1. Introduction
      2. 10.1. Focusing a Text Input on Page Load
      3. 10.2. Disabling and Enabling Form Elements
      4. 10.3. Selecting Radio Buttons Automatically
      5. 10.4. (De)selecting All Checkboxes Using Dedicated Links
      6. 10.5. (De)selecting All Checkboxes Using a Single Toggle
      7. 10.6. Adding and Removing Select Options
      8. 10.7. Autotabbing Based on Character Count
      9. 10.8. Displaying Remaining Character Count
      10. 10.9. Constraining Text Input to Specific Characters
      11. 10.10. Submitting a Form Using Ajax
      12. 10.11. Validating Forms
    16. 11. HTML Form Enhancements with Plugins
      1. Introduction
      2. 11.1. Validating Forms
      3. 11.2. Creating Masked Input Fields
      4. 11.3. Autocompleting Text Fields
      5. 11.4. Selecting a Range of Values
      6. 11.5. Entering a Range-Constrained Value
      7. 11.6. Uploading Files in the Background
      8. 11.7. Limiting the Length of Text Inputs
      9. 11.8. Displaying Labels Above Input Fields
      10. 11.9. Growing an Input with Its Content
      11. 11.10. Choosing a Date
    17. 12. jQuery Plugins
      1. Introduction
      2. 12.1. Where Do You Find jQuery Plugins?
      3. 12.2. When Should You Write a jQuery Plugin?
      4. 12.3. Writing Your First jQuery Plugin
      5. 12.4. Passing Options into Your Plugin
      6. 12.5. Using the $ Shortcut in Your Plugin
      7. 12.6. Including Private Functions in Your Plugin
      8. 12.7. Supporting the Metadata Plugin
      9. 12.8. Adding a Static Function to Your Plugin
      10. 12.9. Unit Testing Your Plugin with QUnit
    18. 13. Interface Components from Scratch
      1. Introduction
      2. 13.1. Creating Custom Tool Tips
      3. 13.2. Navigating with a File-Tree Expander
      4. 13.3. Expanding an Accordion
      5. 13.4. Tabbing Through a Document
      6. 13.5. Displaying a Simple Modal Window
      7. 13.6. Building Drop-Down Menus
      8. 13.7. Cross-Fading Rotating Images
      9. 13.8. Sliding Panels
    19. 14. User Interfaces with jQuery UI
      1. Introduction
      2. 14.1. Including the Entire jQuery UI Suite
      3. 14.2. Including an Individual jQuery UI Plugin or Two
      4. 14.3. Initializing a jQuery UI Plugin with Default Options
      5. 14.4. Initializing a jQuery UI Plugin with Custom Options
      6. 14.5. Creating Your Very Own jQuery UI Plugin Defaults
      7. 14.6. Getting and Setting jQuery UI Plugin Options
      8. 14.7. Calling jQuery UI Plugin Methods
      9. 14.8. Handling jQuery UI Plugin Events
      10. 14.9. Destroying a jQuery UI Plugin
      11. 14.10. Creating a jQuery UI Music Player
    20. 15. jQuery UI Theming
      1. Introduction
      2. 15.1. Styling jQuery UI Widgets with ThemeRoller
      3. 15.2. Overriding jQuery UI Layout and Theme Styles
      4. 15.3. Applying a Theme to Non-jQuery UI Components
      5. 15.4. Referencing Multiple Themes on a Single Page
      6. 15.5. Appendix: Additional CSS Resources
    21. 16. jQuery, Ajax, Data Formats: HTML, XML, JSON, JSONP
      1. Introduction
      2. 16.1. jQuery and Ajax
      3. 16.2. Using Ajax on Your Whole Site
      4. 16.3. Using Simple Ajax with User Feedback
      5. 16.4. Using Ajax Shortcuts and Data Types
      6. 16.5. Using HTML Fragments and jQuery
      7. 16.6. Converting XML to DOM
      8. 16.7. Creating JSON
      9. 16.8. Parsing JSON
      10. 16.9. Using jQuery and JSONP
    22. 17. Using jQuery in Large Projects
      1. Introduction
      2. 17.1. Using Client-Side Storage
      3. 17.2. Saving Application State for a Single Session
      4. 17.3. Saving Application State Between Sessions
      5. 17.4. Using a JavaScript Template Engine
      6. 17.5. Queuing Ajax Requests
      7. 17.6. Dealing with Ajax and the Back Button
      8. 17.7. Putting JavaScript at the End of a Page
    23. 18. Unit Testing
      1. Introduction
      2. 18.1. Automating Unit Testing
      3. 18.2. Asserting Results
      4. 18.3. Testing Synchronous Callbacks
      5. 18.4. Testing Asynchronous Callbacks
      6. 18.5. Testing User Actions
      7. 18.6. Keeping Tests Atomic
      8. 18.7. Grouping Tests
      9. 18.8. Selecting Tests to Run
    24. Index
    25. Colophon
    26. SPECIAL OFFER: Upgrade this ebook with O’Reilly
O'Reilly logo

1.2. Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load


Modern JavaScript applications using unobtrusive JavaScript methodologies typically execute JavaScript code only after the DOM has been completely loaded. And the reality of the situation is that any DOM traversing and manipulation will require that the DOM is loaded before it can be operated on. What’s needed is a way to determine when the client, most often a web browser, has completely loaded the DOM but has possibly not yet completely loaded all assets such as images and SWF files. If we were to use the window.onload event in this situation, the entire document including all assets would need to be completely loaded before the onload event fired. That’s just too time-consuming for most web surfers. What’s needed is an event that will tell us when the DOM alone is ready to be traversed and manipulated.


jQuery provides the ready() method, which is a custom event handler that is typically bound to the DOM’s document object. The ready() method is passed a single parameter, a function, that contains the JavaScript code that should be executed once the DOM is ready to be traversed and manipulated. The following is a simple example of this event opening an alert() window once the DOM is ready but before the page is completely loaded:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript" 
<script type="text/JavaScript">
    jQuery(document).ready(function(){//DOM not loaded, must use ready event
<p>The DOM is ready!</p>


The ready() event handler method is jQuery’s replacement for using the JavaScript core window.onload event. It can be used as many times as you like. When using this custom event, it’s advisable that it be included in your web pages after the inclusion of stylesheet declarations and includes. Doing this will ensure that all element properties are correctly defined before any jQuery code or JavaScript code will be executed by the ready() event.

Additionally, the jQuery function itself provides a shortcut for using the jQuery custom ready event. Using this shortcut, the following alert() example can be rewritten like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript" 
<script type="text/JavaScript">
    jQuery(function(){ //DOM not loaded, must use ready event
<p>The DOM is ready!</p>

The use of this custom jQuery event is necessary only if JavaScript has to be embedded in the document flow at the top of the page and encapsulated in the <head> element. I simply avoid the usage of the ready() event by placing all JavaScript includes and inline code before the closing <body> element. I do this for two reasons.

First, modern optimization techniques have declared that pages load faster when the JavaScript is loaded by the browser at the end of a page parse. In other words, if you put JavaScript code at the bottom of a web page, then the browser will load everything in front of it before it loads the JavaScript. This is a good thing because most browsers will typically stop processing other loading initiatives until the JavaScript engine has compiled the JavaScript contained in a web page. It’s sort of a bottleneck in a sense that you have JavaScript at the top of a web page document. I realize that for some situations it’s easier to place JavaScript in the <head> element. But honestly, I’ve never seen a situation where this is absolutely required. Any obstacle that I’ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.

Second, if speedy web pages are our goal, why wrap more functionality around a situation that can be elevated by simply moving the code to the bottom of the page? When given the choice between more code or less code, I choose less code. Not using the ready() event results in using less code, especially since less code always runs faster than more code.

With some rationale out of the way, here is an example of our alert() code that does not use the ready() event:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<p>The DOM is ready!</p>
<script type="text/JavaScript" 
<script type="text/JavaScript">
     alert(jQuery('p').text());//go for it the DOM is loaded

Notice that I have placed all of my JavaScript before the closing </body> element. Any additional markup should be placed above the JavaScript in the HTML document.

The best content for your career. Discover unlimited learning on demand for around $1/day.