An Introduction to jQuery, Part 1 jQuery is a small JavaScript library that makes development of HTML-based client JavaScript drastically easier. 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. Ok, I admit it. For many, many years I hated JavaScript. I hated writing JavaScript code, and even more I hated the pain that goes along with dealing with different browsers using reams of script code. I still hate the same problems today, 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. 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 12 years ago, but it wasn’t until a few years ago when AJAX surfaced that I even 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: effective use of closures, the Prototype model, class definitions, and using functions as code, all of which require some getting used to when you are primarily dealing with static languages like C# as I do for most of my work. But even knowing JavaScript reasonably well is not enough. These days it’d be silly to work with raw JavaScript for DOM programming and not use some sort of library to help bridge the browser-specific quirks and provide utility functionality to make it easier to work in 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 (www.jQuery.com). jQuery is a relatively small library that is based on a few very simple and intuitive principles. To me, this library strikes the right balance between size, feature set, and ease of use. Even originally after using it for just a few days I already felt like “this is what JavaScript and DOM programming should be!” jQuery can bring 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 me improve my skill set significantly. It’s also made me much more productive and more confident in being able to tackle complex UI and front-end logic in JavaScript reliably. Key Features of jQuery Let me show you why you should take the time to look at jQuery. It has quite a bit of functionality, and I think you should look at these key features: - DOM Element SelectorsjQuery Selectors allow you to 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. Using CSS means that you use selector syntax you’re probably already familiar with from HTML styling and even if 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 relationship to other elements, and you can even chain together filter conditions. Look at this simple example to select all 2nd column TD elements in a table with a simple selector: $("#gdEntries td:nth-child(2)").
- The jQuery Object: The Wrapped SetSelectors result in a jQuery object that is known as the wrapped set, which is an array-like structure that contains each of 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 though, you can also apply jQuery functions against all the selected elements.
- Wrapped Set OperationsThe 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 the matched set 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 allow you to get and set .css() styles directly including smart logic that accounts for browser differences of assignment types (number and string translations mostly) and values (opacity does the right thing on all browsers). You can set and retrieve attributes with .attr(), or retrieve or set a value 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 like .appendTo(), .prependTo(), or reversely use a parent element 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 a smart way that checks for opacity, display, and visibility, and adjusts all to show or hide elements. You can do all of this and much more against all of the selected elements. Most wrapped set operations are also chainable so that they return the jQuery wrapped set object as a result. This means you can chain together many methods in a single command. Effectively this means you can select once and operate many times against the same object and even filter or expand the wrapped set with methods like .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. Methods like .val() or .text() act both as retrieval and setter methods. Methods that deal with numeric values can take 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 a much broader range of functionality that is available on it.
- Simplified Event HandlingMuch of what you do in JavaScript code from DOM manipulation to AJAX calls is asynchronous using events and unfortunately the DOM implementations for event handling vary considerably between browsers. jQuery provides an easy mechanism for binding and unbinding events and providing a normalized event model for all supported browsers that makes it easy to handle events and hook up result handlers. jQuery calls all event handlers in the context of the element that caused the event (i.e., the this pointer) and they receive a fixed up and browser normalized event object that is consistent.
- Small FootprintjQuery is a fairly compact base library yet it’s feature packed with stuff you’ll actually use. In my relatively short time of jQuery use, 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 ExtensibilityjQuery is a language and DOM extension library and it provides a core set of useful features. It’s small and tightly focused on providing core functionality and no more. For everything else, jQuery provides a very easy 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. In this way, plug-ins receive the wrapped set and can operate on it and participate in the jQuery chaining. This very simple but powerful plug-in model is very easy to work with and likely the key to why so many plug-ins exist and 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 with the help of jQuery or another plug-in as a baseline.
Ok, so now that you have some idea of what jQuery provides, I’ll show you how to take it for a spin. In this article, I’ll introduce you to core jQuery concepts of document manipulation purely from a client-side perspective. In part 2, I’ll 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. | & | | 
By: Rick Strahl Rick Strahl is president of West Wind Technologies in Maui, Hawaii. The company specializes in Web and distributed application development and tools, with focus on Windows Server Products, .NET, Visual Studio, and Visual FoxPro. Rick is the author of West Wind Web Connection, West Wind Web Store, and West Wind HTML Help Builder. He’s also a C# MVP, a frequent contributor to magazines and books, a frequent speaker at international developer conferences, and the co-publisher of CoDe Magazine. For more information please visit his Web site at www.west-wind.com or contact Rick at rstrahl@west-wind.com.
rstrahl@west-wind.com | Fast Facts | | jQuery is so intuitive, useful, and practical that it feels criminal to write JavaScript code without it. | |
|