jQuery Cookbook

By Cody Lindley


  • jQuery – is an open source JavaScript library that simplifies the interaction between the DOM and JavaScript (Sizzle is the CSS selector engine behind it)
  • jQuery (JavaScript) Best Practices and Notes
    • jQuery() or $() means new jQuery()
    • (function(){ //code }) – A function wrapper is a typical JS practice for getting local scope
    • (function($) //code })(jQuery); - Is a self-executing anonymous function that enables an alias setup without fear of conflicting with other JS libraries (Sets up $ as an alias to jQuery)
    • var $myDiv = jQuery(’#myDiv’); - Use $ to precede var names accessed via jQuery
    • <script> tags are loaded in the order they appear in the HTML source
    • "map" is a term simply meaning “JavaScript object”
  • jQuery Philosophy – 3 main concepts
    • Find some elements (via CSS selectors) and do something with them
    • Chain multiple jQuery methods on a set of elements (utilizing “wrapper sets”)
    • Use the jQuery wrapper and implicit iteration
  • Selects
    • jQuery(‘a’) – selects all anchor elements in the document
    • jQuery(’#divID a’) – selects all anchor elements in the element with id=’#divID’
    • jQuery(‘p em’) – selects all italic elements within all the paragraph elements
    • jQuery(’#divID p:last’) – selects last paragraph element from the element with id=’#divID’ (:last is a filter)
  • Use the Google-hosted jQuery library and define the <script src="" ) in the <head>
  • Execute when DOM is ready but not all assets (images, swf, etc) are loaded via jQuery(document).ready(function doSomething()); or jQuery(function doSomething());
  • **.end()** means to “return to previous wrapper set”. An example use of this is to clone a set of elements, customize them, and inject them into the document and then use .end() to return to the source of the clone to remove it from the document.
  • If you have a context (a wrapper set or element) use it as opposed to forcing jQuery to go through the selection process again. The default context of jQuery is document, so only provide a context if it is something other than document.
    • i.e. jQuery(‘a’); and jQuery(‘a’, document); are the same but the first is best practice


  • Utility Methods
    • jQuery.each(array, function()) = Iterates over each element in an array (or attribute of an object) and executes the callback function on that element
    • jQuery.grep(array, function()) = Iterates over each element in an array and removes each element that returns false from the callback
    • jQuery.map(array, function()) = Iterates over each element in an array and modifies its value based on the return value of the callback
    • jQuery.unique(array) = removes duplicate DOM elements from an array or collection
  • jQuery(this)
    • In the code for a traditional onevent attribute, this refers to the element receiving the event- but only in the attribute itself, not in a function called from the attribute.
    • It is good practice to set this to a var like so… var $this = jQuery(this);
    • this in an event handler is the window object by default- (this === window; // true)
    • this in a jQuery event handler is the DOM element handling the event
    • Copying this into a local variable (var $this = jQuery(this);) works because JavaScript creates a closure. A closure consists of three simple rules…
      1. Multiple levels of function nesting (functions in functions)
      2. A function can read/write its own parameters and local vars in addition to those of any functions it’s nested in
      3. The previous rule always works (even if the outer function has returned and the inner function is called later, i.e. setTimeout()).


  • jQuerySpeed
    • The speed of jQuery depends on the page in which it is used (it also varies between browsers)
    • Selecting by id (jQuery(#exampleID)) is faster than selecting by class (jQuery(.exampleClass))
    • When iterating large datasets, For loops done in “bare-bones” JavaScript are faster than jQuery utility methods. The catch is that the array must have no “false” elements (i.e. undefined, null, false, 0, or “”), in other JavaScript__is kinda broken terms, it must be “truthy”
  • Reducing Name Lookups- JavaScript’s Lookup order
    1. Local Scope (local function)
    2. Parent Nested Function(s) Scope
    3. Global Scope
    • Be liberal in creating local vars to cache otherwise expensive lookups
  • Reducing Server Requests – It is good practice to…
    1. minify your JavaScript files
    2. Ensure your server is using gzip (compression)
    3. Merge your custom JavaScript files into a single .js file


  • Width and Height
    • jQuery(window).width() & jQuery(window).height()
      • Width/height of the viewport (viewable area of document)
    • jQuery(document).width() & jQuery(document).height()
      • Width/height of the HTML document (scrollbars are used to access portions of the document that reside outside the window bounds)
    • jQuery(element).innerWidth & jQuery(element).innerHeight
      • Returns dimension of the element excluding border and including padding
      • If element is window or document the return value is NaN
    • jQuery(element).outerWidth & jQuery(element).outerHeight
      • Returns dimension of the element including both border and padding
      • If element is window or document the return value is NaN
  • Positions
    • offsetParent – The first parent element with positioning applied to it (i.e. the container)
    • jQuery(’#divID’).offset() – Returns an object containing the position of the top-left corner of the element relative to the document’s top-left corner
    • jQuery(’#divID’).position() – Returns an object containing the position of the top-left corner of the element relative to its offsetParent
    • jQuery(’#divID’).offsetParent() – Returns a jQuery object containing the offsetParent
    • jQuery(window).scrollLeft() - Viewport current X position of the scrollbar
    • jQuery(window).scrollTop() – Viewport current Y position of the scrollbar


  • When specifying properties to animate, use camel case (i.e. marginLeft vs margin-left )
  • Animation
    • Signature
      • jQuery(‘div’).animate(properties, duration, easing, complete);
        • properties – map (object) of CSS properties to animate toward
        • duration – a string or number defining the length of the animation
        • easing – a string indicating the transition ease
        • complete – the callback function executed on animation complete
    • Speeds
      • default = 400ms
      • slow = 600ms
      • fast = 200ms
    • Hidden elements will remain hidden when using .animate() unlike shorthand methods like .slideDown() and .fadeIn() which makes the element(s) visible
  • Animation types (some not all)
    • Slide = jQuery(’#div’).slideToggle(‘slow’);
      • slideUp(), slideDown(), slideToggle()
    • Fade = jQuery(’#div’).animate({ opacity: ‘toggle’}, ‘slow’);
      • fadeIn(), fadeOut(), fadeToggle()
  • arguments.callee is a keyword in JS referring to a local variable that all functions have access to. The arguments object is like an array but lacks all array methods and properties except length
    • arguments.callee is the property that maintains reference to the currently executing function
    • .callee is useful for recursive function calls
  • Easing – All easing functions take 5 parameters
    • fraction – current time position between 0-1
    • elapsed – number of milliseconds passed since animation began
    • attrStart – beginning value of the CSS attribute being animated
    • attrDelta – difference between start and end values of the CSS attribute being animated
    • duration – total number of milliseconds passed during animation


  • Core Event Structure

    • handler example - jQuery(‘div’).bind( 'click** , **** function(e){//}**);
    • shortcut example– jQuery(‘div’).click(function(e){//});
  • Use .bind() to bind a single handler to multiple events and .unbind() to unbind

    • jQuery(‘div’).bind(‘click hover’, function(e){//});
    • jQuery(‘div’).unbind(‘click hover’, function(e){//});
  • Pass an object literal as the second argument of .bind() to map custom data to an event

    • jQuery(’#btn1’).bind(‘click’, {name: ‘Foo’}, function(e){alert('Clicked ’ + e.data. name)};
  • Namespaces

    • Use a namespace to bind/unbind many events at once
    • Add a namespace to an event with…
      • **$.fn.myPlugin = function(){ return this.bind(‘click.myPlugin’, function(){//});**
    • Remove all event handlers in a namespace
      • **$.fn.disposeMyPlugin = function(){ return this.unbind(’.myPlugin’);**
  • Polling – Is the process by which setInterval() is used to check for an element, and once found, a function is executed and the interval cleared. This is often used when trying to access an element(s) before document.ready() has been reached

  • Utilize .stop(true) to kill existing animations before creating a new one.

  • Utilize Event Delegation for elements with many children elements that have listeners applied

  • Use jQuery.event.special for custom events (mousewheel, drag/drop, focusin/focusout use this)


  • jQuery.fn is an alias to jQuery.prototype , itexits for backwards compatibility, it is also how you write plugins. (i.e. jQuery.fn.myPlugin = function(){alert(‘Winning’)};
  • Writing a custom jQuery function is as easy as jQuery.** customFunction****(){alert(‘Winning’)}**;
  • It is best practice to use an options object for passing in arguments to a custom plugin because…
    • Cleaner code
    • Flexibility (can have defaults and can be overridden)
  • Use QUnit to test plugins for quality and reliability
  • jQueryUI is a sister project that provides a core set of interaction plugins (UI widgets and components)

AJAX and Data Formats

  • jQuery.ajax({type: ‘GET’, url: ‘hello-ajax.html’, dataType: ‘html’, success: function(){alert(‘Winning’)}, error: function(){alert(‘Losing’)}}); is an example ajax GET request.
  • The types include xml, html, script, json, jsonp, or text
  • Ajax events (in trigger order)
    • ajaxStart – triggered at start of Ajax request if no other requests are in progress
    • ajaxSend – triggered before each individual request is sent
    • ajaxSuccess/ajaxError – triggered on success or error of request
    • ajaxComplete – triggered every time request completes (success or error)
    • ajaxStop – triggered if there are no additional Ajax requests in progress
  • Ajax event order on successful/unsuccessful Ajax request
    • ajaxStart (global)
    • beforeSend (local)
    • ajaxSend (global)
    • success/error (local)
    • ajaxSuccess (global) - ajaxError (local) - (may both be global, text misprint possibly)
    • complete (local)
    • ajaxComplete (global)
    • ajaxStop (global)
  • JSON – JavaScript Object Notation is a standard for exchanging data from browser to server
    • Serialization – encoding an object into its string representation
    • Deserialization – decoding a string representation into an object literal
  • JSONP – JSON with Padding – it provides a method to request data from a server in a different domain (something prohibited by typical web browsers)