Since you’ve picked up a cookbook about jQuery, the authors of this book for the most part are going to assume that you have a loose idea about what exactly jQuery is and what it does. Frankly, cookbooks in general are typically written for an audience who seeks to enhance a foundation of knowledge that has already been established. Thus, the recipe-solution-discussion format is used to quickly get you solutions to common problems. However, if you are a jQuery newbie, don’t throw this book against the wall and curse us just yet. We’ve dedicated this chapter to you.
With that said, let’s take a look at a formal definition of jQuery and a brief description of its functionality:
With a formal explanation of jQuery under our belts, let’s next explore why you might choose to use jQuery.
So, while I might be preaching to the choir here, we’re going to take a quick look at why a developer might choose to use jQuery. My point in doing this is to foster your basic knowledge of jQuery by first explaining the “why” before we look at the “how.”
In building a case for jQuery, I’m not going to compare jQuery to its competitors in order to elevate jQuery’s significance. That’s because I just don’t believe that there really is a direct competitor. Also, I believe the only library available today that meets the needs of both designer types and programmer types is jQuery. In this context, jQuery is in a class of its own.
It’s open source, and the project is licensed under an MIT and a GNU General Public License (GPL) license. It’s free, yo, in multiple ways!
It’s small (18 KB minified) and gzipped (114 KB, uncompressed).
It’s incredibly popular, which is to say it has a large community of users and a healthy amount of contributors who participate as developers and evangelists.
It normalizes the differences between web browsers so that you don’t have to.
It’s intentionally a lightweight footprint with a simple yet clever plugin architecture.
Its repository of plugins is vast and has seen steady growth since jQuery’s release.
Its community support is actually fairly useful, including several mailing lists, IRC channels, and a freakishly insane amount of tutorials, articles, and blog posts from the jQuery community.
It’s openly developed, which means anyone can contribute bug fixes, enhancements, and development help.
Its development is steady and consistent, which is to say the development team is not afraid of releasing updates.
Its adoption by large organizations has and will continue to breed longevity and stability (e.g., Microsoft, Dell, Bank of America, Digg, CBS, Netflix).
It’s incorporating specifications from the W3C before the browsers do. As an example, jQuery supports a good majority of the CSS3 selectors.
It’s currently tested and optimized for development on modern browsers (Chrome 1, Chrome Nightly, IE 6, IE 7, IE 8, Opera 9.6, Safari 3.2, WebKit Nightly, Firefox 2, Firefox 3, Firefox Nightly).
It’s downright powerful in the hands of designer types as well as programmers. jQuery does not discriminate.
Its unexplainable by-product of feel-good programming is contagious and certainly unavoidable; even the critics seem to fall in love with aspects of jQuery.
Its documentation has many outlets (e.g., API browser, dashboard apps, cheat sheets) including an offline API browser (AIR application).
Its learning curve is approachable because it builds upon concepts that most developers and designers already understand (e.g., CSS and HTML).
Finding some elements (via CSS selectors) and doing something with them (via jQuery methods)
Chaining multiple jQuery methods on a set of elements
Using the jQuery wrapper and implicit iteration
Understanding these three concepts in detail is foundational when it comes time to write your own jQuery code or augment the recipes found in this book. Let’s examine each of these concepts in detail.
Or more specifically stated, locate a set of elements
in the DOM, and then do something with that set of elements. For
example, let’s examine a scenario where you want to hide a
<div> from the user, load some new
text content into the hidden
<div>, change an attribute of the
<div>, and then
finally make the hidden
<div> visible again.
This last sentence translated into jQuery code would look something like this:
Let’s step through these four jQuery statements:
element on the page so it’s hidden from the user’s view.
Replace the text inside the hidden
<div> with some new text
element with a new attribute (
class) and value (
element on the page so it’s visible again to the viewing
If the jQuery code at this point is mystical syntax to you,
that’s OK. We’ll dive into the basics with the first recipe in this
chapter. Again, what you need to take away from this code example is
the jQuery concept of “find some elements and do something with
them.” In our code example, we found all the
<div> elements in the HTML page
using the jQuery function (
jQuery()), and then using jQuery methods
we did something with them (e.g.,
This code, using chaining, can be changed from this:
//hide all divs on the page jQuery('div').hide(); //update the text contained inside of the div jQuery('div').text('new content'); //add a class attribute with a value of updatedContent to all divs jQuery('div').addClass("updatedContent"); //show all divs on the page jQuery('div').show();
or, with indenting and line breaks, to this:
jQuery('div') .hide() .text('new content') .addClass("updatedContent") .show();
Plainly speaking, chaining simply allows you to apply an endless chain of jQuery methods on the elements that are currently selected (currently wrapped with jQuery functionality) using the jQuery function. Behind the scenes, the elements previously selected before a jQuery method was applied are always returned so that the chain can continue. As you will see in future recipes, plugins are also constructed in this manner (returning wrapped elements) so that using a plugin does not break the chain.
If it’s not immediately obvious, and based on the code in question, chaining also cuts down on processing overhead by selecting a set of DOM elements only once, to then be operated on numerous times by jQuery methods by way of chaining. Avoiding unnecessary DOM traversing is a critical part of page performance enhancements. Whenever possible, reuse or cache a set of selected DOM elements.
A good majority of the time, if jQuery is involved,
you’re going to be getting what is known as a
wrapper. In other words, you’ll be selecting
DOM elements from an HTML page that will be wrapped with jQuery
functionality. Personally, I often refer to this as a “wrapper set”
or “wrapped set” because it’s a set of elements wrapped with jQuery
functionality. Sometimes this wrapper set will contain one DOM
element; other times it will contain several. There are even cases
where the wrapper set will contain no elements. In these situations,
the methods/properties that jQuery provides will fail silently if
methods are called on an empty wrapper set, which can be handy in
Now, based on the code we used to demonstrate the “Find some
elements and do something with them” concept, what do you think
would happen if we added multiple
<div> elements to the web page? In
the following updated code example, I have added three additional
<div> elements to the HTML
page, for a total of four
You may not have explicitly written any programmatic loops
here, but guess what? jQuery is going to scan the page and place all
<div> elements in the
wrapper set so that the jQuery methods I am using here are performed
(aka implicit iteration) on each DOM element in the set. For
actually applies to each element in the set. So if you look at our
code again, you will see that each method that we use will be
applied to each
element on the page. It’s as if you had written a loop here to
invoke each jQuery method on each DOM element. The updated code
example will result in each
<div> in the page being hidden,
filled with updated text, given a new class value, and then made
Wrapping your head around (pun intended) the wrapper set and
its default looping system (aka implicit iteration) is critical for
building advanced concepts around looping. Just keep in mind that a
simple loop is occurring here before you actually do any additional
another way to look at this is each element in the wrapper will
typically be changed by the jQuery method(s) that are called.
Something to keep in mind here is there are scenarios that you
will learn about in the coming chapters where only the first
element, and not all the elements in the wrapper set, is affected by
the jQuery method (e.g.,
Before you really get started with jQuery, I suggest visiting the documentation online and simply digesting how the API is organized. By understanding how the API is organized, you’ll more quickly navigate the documentation to the exact information you need, which is actually a significant advantage given that there are really a lot of different ways to code a jQuery solution. It’s so robust that it’s easy to get hung up on implementation because of the number of solutions for a single problem. I’ve replicated here for you how the API is organized. I suggest memorizing the API outline, or at the very least the top-level categories.
The jQuery Function
jQuery Object Accessors
Height and Widths
Browser and Feature Detection
Array and Object Operations
Before we jump into a sequence of basic jQuery recipes, I would like to mention that the recipes found in this chapter build on each other. That is, there is a logical formation of knowledge as you progress from the first recipe to the last. It’s my suggestion, for your first reading of these recipes, that you read them in order from 1.1 to 1.17.