RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


An Introduction to jQuery, Part 1

jQuery is a small JavaScript library that makes development of HTML-based client JavaScript drastically easier.

k, I admit it. For many, many years I hated JavaScript. I hated writing JavaScript code, and I hated the pain that goes along with dealing with different browsers using reams of script code even more. I still hate those same problems, but thanks to a recently-gained better understanding of JavaScript and a small JavaScript client library called jQuery, I no longer dread the days when I have to write client-centric AJAX script code. In fact, I welcome them now! With client logic getting ever more complex and browsers still diverging in features and implementation of features, jQuery and other client libraries provide much needed normalization when working with JavaScript and the HTML DOM.

I started out as a JavaScript neophyte—and stayed that way for a long time. Sure I used JS here and there for validation and few simple manipulation tasks, but it wasn't until a few years ago when AJAX surfaced that I took a more serious interest. It took me some time after that to slowly get up to speed on modern JavaScript principles I had never even thought about up until then, such as: effective use of closures, the Prototype model, class definitions, and using functions as code—all of which require some getting used to when you deal primarily with static languages such as C#.

But even knowing JavaScript reasonably well is not enough. These days it'd be silly to work with raw JavaScript for DOM programming without using some sort of library to help bridge the browser-specific quirks and provide utility functionality and a browser-agnostic environment. I've checked out a number of different libraries over the last couple of years, but the one that really grabbed me is jQuery, a relatively small library based on a few very simple and intuitive principles. This library seems to strike the right balance between size, feature set, and ease of use. Even after using it for only a few days I felt comfortable.

jQuery offers tremendous productivity gains, and it's easy to learn and work with. It's one of those tools that has drastically changed how I think about client-side development, and frankly, it has helped improve my skill set significantly. It's also made me more productive and given me the confidence that I can tackle complex UI and front-end logic in JavaScript reliably.

jQuery is so intuitive, useful, and practical that it feels criminal to write JavaScript code without it.

Key Features of jQuery

To evaluate jQuery, you should look at these key features:

  • DOM Element Selectors: jQuery Selectors let you select DOM elements so that you can apply functionality to them with jQuery's operational methods. jQuery uses a CSS 3.0 syntax (plus some extensions) to select single or multiple elements in a document. You're probably already familiar with the CSS syntax from HTML styling. Even if you're not, it's fairly easy to pick up the key CSS selector features. I'll go as far as saying that jQuery is the reason I really started to grok CSS. Using CSS syntax you can select elements by ID, CSS class, attribute filters, or by their relationship to other elements. You can even chain filter conditions together. Look at this simple example, which selects all second-column TD elements in a table using a simple selector: $("#gdEntries td:nth-child(2)").
  • The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example). More importantly, you can also apply jQuery functions against all the selected elements.
  • Wrapped Set Operations: The real power of the wrapped set comes from applying jQuery operations against all selected DOM elements simultaneously. The jQuery.fn object exposes about 100 functions that can operate on wrapped sets, and allows you to manipulate and retrieve information from the selected DOM objects in a batch. For example, you can easily manipulate all alternate rows in a table by adding a CSS class with $("#gdEntries tr:odd").addClass("gridalternate"). jQuery applies the .addClass() function against each of the matched elements with one command. Intuitive methods such as .css() let you get and set CSS styles directly, and include smart logic that accounts for browser differences in assignment types (number and string translations mostly) and values (for example, opacity does the right thing on all browsers, even though different browsers treat it differently). You can set and retrieve attributes with .attr(), or retrieve or set values with .val(), .text(), or .html(). You can clone selected DOM elements or create new elements from HTML text used as a selector and inject them into the document with methods such as .appendTo() and .prependTo(). You can find and use a parent element to which to .append() or .prepend() the new or selected element(s). You can apply some basic but useful effects methods to .show() and .hide() elements in an intelligent manner that checks for opacity, display, and visibility, and adjusts all those values to show or hide elements. Remember, you can do all of this (and much more) against all of the selected elements in a wrapped set.
  • Most wrapped set operations are also chainable; they return the jQuery wrapped set object as a result. This means you can chain many methods together in a single command. Effectively, this means you can select once and subsequently operate many times against the same object. You can even filter or expand the wrapped set with methods such as .find(), .filter(), or .add(). The beauty of many of these functions is that they do things you actually want to do, and they are intuitively overloaded. For example the .val() and .text() methods work for both retrieval (getter) and setter methods. Methods that deal with numeric values can accept either text or numeric values. jQuery automatically fixes CSS assignments to browser-dependent tags. Although the number of functions provided by jQuery is relatively small, many of the functions provide overloaded functionality to perform intuitive behaviors. The end result is that you have a relatively small API to learn, but one that provides a broad range of functionality.
  • Simplified Event Handling: Much of what you do in JavaScript code from DOM manipulation to AJAX calls is asynchronous, and requires using events. Unfortunately, DOM implementations for event handling vary considerably between browsers. jQuery provides an easy mechanism for binding and unbinding events and a normalized event model that makes it easy to handle events and hook up result handlers for all supported browsers. jQuery calls all event handlers in the context of the element that caused the event (i.e., the this pointer). The handlers receive a consistent fixed-up and browser-normalized event object.
  • Small FootprintjQuery is a fairly compact base library, yet it's packed with features you'll actually use. During my relatively short time using jQuery, I've gone through well over 85% of the jQuery functions with my code, which points at how useful the library is. All this functionality ends up in a compressed size of just around 16 KB (94 KB uncompressed with comments). For that you get selectors, a whole slew of operations that you can perform on the wrapped set, DOM normalization for most browsers, AJAX functionality, a host of utility functions for object/array manipulation, and a number of basic effect functionality. Given my high utilization of jQuery, this 16 KB of script download provides a tremendous amount of "Bang for the Buck."
  • Easy Plug-in Extensibility: When jQuery's language and DOM extension library features aren't enough, jQuery provides a simple plug-in API that has spawned hundreds of plug-ins for almost every conceivable common operation you might think up to perform on a set of DOM elements. jQuery's API allows extending the core jQuery object's operations simply by creating a function and passing the jQuery wrapped set as a parameter, which lets plug-ins operate on it and participate in jQuery chaining. This simple but powerful plug-in model is likely the key to both the large number of plug-ins exist and the reason why jQuery has become so popular so quickly. If you need some specialty functionality, chances are that a plug-in already exists with the functionality you're looking for—and if it doesn't, it's easy enough to create it yourself or extend an existing plug-in.
Ok, so now that you have some idea of what jQuery provides, I'll show you how to take it for a spin. This article introduces the jQuery concepts of document manipulation purely from a client-side perspective. A follow-up article will discuss how to use jQuery in combination with ASP.NET on the server for AJAX callbacks, and how to integrate jQuery with server-side controls and components.

Editor's Note: This article was first published in the January/February 2009 issue of CoDe Magazine, and is reprinted here by permission.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date