At the Forge - jQuery Plugins
Last month, we began to look at jQuery, an open-source JavaScript library that provides a great deal of functionality for Web developers, which is increasingly popular for client-side application development. We saw that jQuery's use of CSS-style selectors, combined with its “chaining” syntax, makes it easy to get started with the library and to attach behaviors to page elements. We also saw that jQuery inherently is unobtrusive, with event handlers being assigned via $(document).ready(), rather than inline with the HTML.
At the end of the day though, jQuery does many of the same things as Prototype, YUI and other JavaScript libraries. So, why have so many developers moved to jQuery? What makes it such an attractive choice? Speed and the API are obviously two factors, but a major reason for developers to use jQuery is the huge library of plugins that is available for it. Just as Perl programmers can enjoy a massive library of modules known as CPAN, jQuery users can benefit from a large number of plugins for a variety of tasks, from UI elements to AJAX form submission. Installing and using a jQuery plugin is extremely straightforward, and it can be installed (and evaluated) in minutes.
This month, let's look at a few of the many jQuery plugins that have been developed over the last few years, and also at how to use plugins to change our Web applications.
From a developer's perspective, a jQuery plugin is nothing more than an additional JavaScript file that you download, install in your Web application's JavaScript directory, include in your program with a <script> tag and then invoke. Typically, a plugin adds one or more new functions to the jQuery object, which means if you install a plugin named foo, you often can do the following:
$(document).ready(function() { $('#mybutton').foo(); }
The above construct tells jQuery that when the HTML document has been downloaded enough to start querying and modifying it with JavaScript, you invoke a function. That function, in turn, looks for an HTML element with the ID mybutton and then invokes the foo() method on it.
What does $('#mybutton').foo() do? That's up to the author of the plugin. Typically, a plugin adds functionality to an element or class of elements, quite possibly modifying the HTML around that element—adding new elements necessary for the plugin to do its job or adding classes that cause one or more CSS declarations to be invoked.
Because a jQuery plugin typically modifies the document's HTML, it's vitally important to look at a plugin's documentation to understand what HTML structure it expects to receive. Perhaps it expects to have an unordered list (<ul>) with list items (<li>) inside it. Perhaps it expects to have <div> tags with <span> tags inside it. Perhaps it expects something else altogether. If a plugin doesn't seem to do what you expected, double-check that your HTML matches the example and/or what's in the documentation.
jQuery plugins also rely in no small part on the powerful visualizations that CSS provides. Installing a jQuery plugin often means not only using JavaScript code, but also putting CSS styles into effect—either by incorporating the plugin's CSS file into your application or by copying the declarations into an existing CSS file. Just as many plugins require that your HTML be structured a certain way in order to work, some require that you set certain classes or IDs on your HTML elements.
The fact that jQuery plugins modify the HTML and/or CSS means that you might need some extra tools to understand and debug what is happening in your browser. I normally develop in Firefox, and I have found the Firebug extension to be a wonderful tool to identify issues and experiment with alternatives, in both JavaScript and CSS. Also quite valuable is the Web Developer extension for Firefox, whose “view generated HTML” does the same thing as “view source”, but shows you the HTML as it currently exists, not as it was downloaded originally from the server before JavaScript modified it.
Finally, some plugins come with images that enhance the way the plugin works.
The way I've described it so far might make it seem as though jQuery plugins are difficult to use or that they will force you to change and contort your HTML in numerous ways. But, nothing is further from the truth. On the contrary, the main problem I have had with jQuery plugins is the vast variety and scope of them, forcing me to choose among 20 different menuing plugins or ten different modal-dialog plugins. Comparing and evaluating these plugins, many of which have borrowed code from one another, can be difficult. But, when you find an appropriate plugin, it's usually quite easy to get started using it.
If you are trying to do something in jQuery that others probably have tried before, you always should look through the main plugin repository first, at plugins.jquery.com. There also is a large library of user-interface (UI) plugins at ui.jquery.com. And of course, large numbers of plugins are described, documented and downloadable from Web sites outside jquery.com.
HTML tables have been around for many years, and although they have gotten a bad reputation because of the way they were used and abused for layout purposes (even after the introduction of CSS), there are many times when a table is the best and most logical way to present data. If you are running an on-line store, for example, and you want to get a summary of recent orders, it makes sense to structure the data in a table.
One of the most common things users want to do with a table, once they see it, is sort the rows according to one particular column. To continue with our e-commerce example, perhaps they want to sort the list by order number. Or, perhaps they want to sort it by customer name, by price or by date.
It's not hard to do this kind of sorting on the server side. Set up the table headers to be clickable links, and when you get a request, you change the order of the rows before they are output. But, if the data already is in your browser, wouldn't it be nice to be able to sort the rows in JavaScript? This might not be the fastest possible way to execute such a sort, but given small enough data sets, it's acceptable for most purposes, and it gives the user a sense of desktop-like control and response.
One nice jQuery plugin I've found to do this is called DataTable, written by Allan Jardine (see Resources). DataTable takes an existing HTML table and makes it sortable by column, as well as searchable.
To get this to work, you need an HTML table. Listing 1 is an HTML file that will work just fine for these purposes, although you presumably will want to use DataTable with a dynamic Web application.
Listing 1. table.html
<html> <head> <title>Testing tables</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.dataTables.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#people-table').dataTable(); }); </script> </head> <body> <h1>Testing tables</h1> <table id="people-table"> <thead> <tr> <th>ID</th> <th>Last Name</th> <th>First Name</th> <th>City</th> <th>Balance</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Lerner</td> <td>Reuven</td> <td>Modi'in</td> <td>100</td> </tr> <tr> <td>2</td> <td>Barack</td> <td>Obama</td> <td>Washington</td> <td>750000000</td> </tr> <tr> <td>3</td> <td>Bush</td> <td>George</td> <td>Dallas</td> <td>-1000000000</td> </tr> </tbody> </table> </body> </html>
As you can see, Listing 1 contains a single table with an ID of people-table. The table is defined as you might expect for an HTML table, with one possible exception (unless you're extremely pedantic). The headers for the table are defined with a <thead> section, while the body is in a <tbody> section. These tags are optional according to the HTML standard, but they are mandatory if you want to use DataTable.
With the table in place, you now can add jQuery and the DataTable plugin. Unlike other sorts of plugins, there's nothing to install, except the JavaScript file itself. If you put jquery.js and dataTable.js in the same directory as the file (which is probably not a good idea on a production system), you can write:
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.dataTables.js"></script>
Now everything is ready, except one thing. You need to connect the DataTable plugin to your table. You do this by telling JavaScript that when the document is ready, you want to connect the two:
$(document).ready(function () { $('#people-table').dataTable(); });
If you aren't familiar with jQuery already, you'll soon learn that this is a common idiom when using the library. Define a function that is triggered on $(document).ready and have that function execute and/or define a number of other items, each of which fires on a different tag, ID or class.
Once you connect DataTable to the table, you'll see that the headers are now clickable and force the table to be sorted, first in ascending and then in descending order. (The DataTable download includes icons and CSS appropriate for seeing the sort order.)
DataTable supports a large number of options, all of which are passed to the dataTable() function. For example, DataTable shows ten rows of the current table by default, but it lets you choose from 10, 25, 50 and 100 rows. If you prefer to see a different number, you can set the iDisplayLength property to a different default:
$(document).ready(function () { $('#people-table').dataTable({'iDisplayLength': 1}); });
I recently have used DataTable in a few projects, and I've found it to be easy to use, stable and well documented. The biggest problems crop up when you have a large data set, but that's not unique to DataTable.
Another common task people want to do in JavaScript is produce menus, including hierarchical menus. Indeed, if I think back several years, menus probably are one of the things for which my clients have most commonly asked. One of the best-known methods for creating menus with CSS is known as Suckerfish, because of the sample data that was used to show the technique.
There are many jQuery-based menu libraries, but one I've grown to enjoy is called Superfish, because it adds functionality to the Suckerfish style of menu. It handles submenus, adds shadows and even tries to be intelligent about when you plan to open the menu and when your mouse is passing by, using a separate plugin known as hoverIntent.
To use Superfish, you need to download and install the plugin. Then, you need to create a menu using a combination of <ul>, <li> and <a> tags. If you need a secondary hierarchy of menus, you can create one with a nested <ul> in an <li> tag. In each <a> tag, the href identifies which div on a page should be displayed when that menu item is clicked on, hiding all of the other divs by default.
You undoubtedly will want to start off with the Superfish CSS file that comes with the plugin. You always can modify it to suit your needs. There are large numbers of definitions, and I've never been able to build the CSS file from scratch. Instead, I've modified the existing one, changing it to suit my needs.
As always in jQuery, you use the plugin by attaching it to an element of the HTML page. Instead of using the element's ID, as you did with DataTable, here you attach it to the <ul> tag with a class of sf-menu:
<script type="text/javascript"> $(document).ready(function () { jQuery('ul.sf-menu').superfish(); }); </script>
If there were more than one <ul> with that class, Superfish would create menus on all of them. Remember, the jQuery object can return any number of page elements: zero, one or a large number. The full HTML for the example is shown in Listing 2.
Listing 2. menu.html
<html> <head> <title>Testing menus</title> <link rel="stylesheet" type="text/css" media="screen" href="superfish.css" /> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="superfish.js"></script> <script type="text/javascript"> $(document).ready(function () { jQuery('ul.sf-menu').superfish(); }); </script> </head> <body> <h1>Testing menus</h1> <div> <ul class="sf-menu sf-navbar"> <li> <a href="">Account</a> <ul> <li><a id="checking-menu" href="#checking-div">Checking</a> </li> <li><a id="savings-menu" href="#savings-div">Savings</a> </li> <li><a id="credit-card-menu" href="#credit-card-div"> Credit card </a> </li> </ul> </li> <li><a id="profile-menu" href="#profile-div">Profile</a> </li> <li><a id="help-menu" href="#help-div">Help</a> </li> </ul> </div> </body> </html>
Plugins are the secret to jQuery's success, and there are so many plugins for jQuery, it's impossible to describe them all here. But, as you can see from these two examples, using the plugin often requires very little effort. Once you get the hang of it, downloading, installing and using plugins becomes second nature. I've found it can be useful to create a simple, small HTML file with dummy data and use a jQuery plugin with that, just to understand the basics of how to use a plugin.
There are times when plugins clash with one another, in that they're both trying to rewrite the HTML, sometimes in conflicting ways. For example, I recently used DataTable along with with a jQuery tab widget, and it took me a while until I could ensure that everything was visible on the page. As jQuery plugins become increasingly sophisticated, we might have to worry about this more and more.
For now, however, jQuery plugins are a fun and easy way to spruce up your Web application. Next month, I'll explain how to design your own plugin, delving a bit deeper into jQuery's plumbing and understanding how jQuery takes advantage of JavaScript's quirks to give us an extensible platform for client-side programs.
Resources
The jQuery home page is at www.jquery.com, and it includes a large number of links to tutorials and articles about the library.
The home page for the DataTables plugin is www.sprymedia.co.uk/article/DataTables.
The original article introducing CSS Suckerfish drop-down menus is at www.alistapart.com/articles/dropdowns. The Superfish jQuery plugin is at www.alistapart.com/articles/dropdowns.
If you are a Ruby on Rails developer and are interested in using jQuery (instead of the default Prototype and Script.aculo.us), you can learn more by reading errtheblog.com/posts/73-the-jskinny-on-jquery.
Reuven M. Lerner, a longtime Web/database developer and consultant, is a PhD candidate in learning sciences at Northwestern University, studying on-line learning communities. He recently returned (with his wife and three children) to their home in Modi'in, Israel, after four years in the Chicago area.