Ten Amazing jQuery Plugins (Javascript And Ajax)

The jQuery library is amazing enough on its own, but it has yet another wonderful surprise up its sleeve: a marvelous plugin interface that makes new plugins or extensions to the library easy to add.
The plugins do many things, from changing the way your page looks to including audio and simplifying certain AJAX calls. This chapter contains a sampling of jQuery plugins I’ve found useful, but there are many more available at the jQuery main site (http://plugins.jquery.com/).

Using the Plugins

Each plugin is different, but the general approach to using them is the same:

1. Visit the appropriate Web page.
Check the jQuery main site for a list of jQuery plugins (http:// plugins.jquery.com). You can download each plugin from the jQuery site or get a link to the plugin’s home page, where you’ll generally find more complete help information.
2. Download the plugin.
Most plugins are simply JavaScript files. Often other support material is available as well, including documentation, CSS files, and examples. Be sure to install the files you need in the working directory.
3. Create a basic XHTML page.
Check the documentation to see what elements you need. Most jQuery plugins modify or replace some existing element in the Web page.
4. Add an init() function.
Most jQuery functions (including plugins) require some sort of initialization function.
5. Call the appropriate jQuery function.
Most plugins just add new functions to jQuery. For the most part, you’ll apply these functions to jQuery nodes just as you would for a normal use of jQuery.
6. Customize.
In this introduction, I tend to show the most basic form of each plugin for simplicity’s sake. Be sure to check the documentation for each plugin to see how you can customize it; many plugins do far more than I have the space to show you in this chapter.
I’ve tended to include the simpler and more representative plugins in this chapter. I’ve omitted a number of especially useful plugins because they either require a special license (as the Google Maps plugin does) or require support for a database or PHP (as many of the cooler AJAX plugins do). Spend some time at http://plugins.jquery.com/ to see the astonishing variety of plugins available.

ipWEditor

One very popular AJAX technique is to make a portion of the Web page editable. The ipwEditor plugin (www.spacebug.com/IPWEditor_In-Place_ WYSlWYG_Editor) combines two different approaches to this issue, making it easy to turn ordinary pages into a simple content management system. First, take a look at the editable plugin (included with ipwedit or available on its own).

Adding a basic editor with editable

First, take a look at a very basic editor in Figure 15-1.
When you click the paragraph, it turns into an editable text area. The user can place her own text or HTML in the area and click the Done button to save the text. See Figure 15-2 for the editor in action.
The changes made are not permanent, but you could easily add an AJAX function to send the new data to a server-side script to make a permanent change to the page.
You obviously don’t want to allow just anybody to make page changes. You’ll probably want to have some sort of login system to ensure that only authorized people get access to the version of the page with editing enabled.
This page has a hidden feature.
Figure 15-1:
This page has a hidden feature.
The editor automatically pops up and lets the user change the page.
Figure 15-2:
The editor automatically pops up and lets the user change the page.
tmp18755_thumb_thumbtmp18756_thumb_thumb

Here’s what you do to incorporate the simple editor:

1. Include the jquery.editable or jquery.editable.wysiwyg script.
All the functionality you need for this example is provided in the
jquery.editable plugin. However, the jquery.editable.wysiwyg plugin includes both this script and the more elaborate wysiwyg editor as well.
2. Create an HTML area to edit.
In this example, I edit a div called basicEdit. In a production example, you might make each div or paragraph editable.
3. Apply the editable function.
After the editable plugin is available, you can simply apply the editable function to all the jQuery elements you want to have editable behavior.
4. Specify the button text.
The second parameter of the plugin is the text that will go on the supplied button.
5. Save the data.
This particular example does nothing with the changed text, so it has limited functionality. In a production version of the program, you’ll probably write some sort of AJAX code to package up all the new text and send it to a server-side program for processing and saving.

Incorporating more advanced editing with FCKedit

The ipwEditor includes the simple plugin (called the jquery editable plugin) and a second more sophisticated plugin. This second plugin allows a much more sophisticated editor to appear, with a word-processor-like user interface. If you’ve played around with content management systems, the chances are you’ve seen this interface, shown in Figure 15-3.
Now the page has two editable areas.
Figure 15-3:
Now the page has two editable areas.
This example keeps the basic editor, but if you click the second paragraph, a much more elaborate editor appears, shown in Figure 15-4.
This editor looks a lot like a word processor.
Figure 15-4:
This editor looks a lot like a word processor.
The wysiwyg plugin adds the functionality of another very popular library called FCKedit (www.fckeditor.net/). This popular editor is used in many content management systems, and it’s quite powerful and easy to modify. The FCKedit library is included with the ipwEditor plugin. The editable. wysiwyg plugin makes it easy to add FCKedit to your pages. Here’s the code:
tmp18759_thumb_thumbtmp18760_thumb_thumb

This code is a bit more elaborate than the standard editable plugin, because it requires initialization of the (included) fckEdit library. Here’s how it works:

1. Be sure to have the fckeditor folder in your working directory.
This library is included with the jquery.editable.wysiwyg download.
2. Build a Web page with editable areas.
Build your XHTML page as normal, considering which segments you want editable.
3. Include the fckeditor script.
The fckeditor script is a js file available in the fckeditor folder. Include this script so your page will have access to the editor.
4. Create an instance of the fckeditor class.
In your initialization function, create a single fckeditor variable. This will initialize fckeditor.
5. Indicate the fckeditor base path.
This helps fckeditor find all its helper files in the subdirectory.
6. Apply the editable function to any elements you want to make editable.
This process works exactly the same as the basic editable plugin.
7. Set the type to wysiwyg.
The wysiwyg version of the editable plugin adds the capability to change your editor type.
8. Apply the editor.
Set the editor parameter to the fckeditor variable you created in
Step 4.
9. Set the text of the Submit button.
As in the simpler editable area, a Submit button appears automatically. Set the text of this button with this parameter.
10. Set a callback function if you want.
You can apply a callback function to editable objects; it indicates a function to send after submission is complete. Usually this function does some error-checking and then sends the new contents to a server-side script via AJAX. My version just displays the new contents.
The results of any edit are still HTML, which is ultimately plain text. You should be cautious with any changes you allow the user to make, because malicious users can cause you some major headaches.

jQuery Cookies

Cookies are a useful Web tool, even if they are somewhat misunderstood. A cookie is a simple text message that can be stored and received on the client
by either the client or server programs. The type of data is severely limited, but this can still be a very useful tool:
Each cookie is a name / value pair: You can think of a cookie as a variable you can save on the client.
Cookies are simply text data: If you want another kind of data, convert it to text for storage.
Cookies are saved in a large text file: Different browsers have different mechanisms, but in essence all the cookies saved by a particular user on a particular browser are saved in one text file.
Cookies have size limits: It’s not appropriate to store (for example) an entire database in a cookie. It’s more common to keep login status so the system can make a request to a server-side database.
Cookies are mainly used to store state data: The most common use of cookies is to keep track of a user’s status with the application. Usually the server does all the heavy lifting.
Managing cookies is not difficult, but it’s made even easier by a couple of tools. There’s an amazing plugin called jquery.cookies (http://code. google.com/p/cookies/), which makes this job extremely painless.

Take a look at the code for cookies.html, which uses this plugin:

tmp18761_thumb_thumbtmp18762_thumb_thumb

The process is painless:

1. Include the jquery.cookies script.
As always, include jQuery and the script for this plugin.
2. Use the $.cookies function to manage cookies.
This function encapsulates the content of the cookies library.
3. Use $.cookies.set() to create a cookie and set its value.
If the cookie does not exist, it is created, and the specified value is added to the cookie.
4. Use $.cookies.get() to retrieve the value of the cookie. The get() function is an easy way to retrieve data from a cookie.
5. Look over the documentation for more options.
The cookies library has more features — including the capability to check whether the browser is accepting cookies, to determine whether a cookie exists, to delete cookies, and more.
I didn’t provide a screen shot for this program, because all the interesting stuff happens under the hood. Take a look at cookies.html on the Web page for the topic to see it in action.

Flot

Sometimes your Web pages need to display some kind of data. You can use any of various powerful graphing plugins for that purpose. One easy and powerful option is called flot, available at http://code.google.com/p/ flot/. Figure 15-5 shows this tool in action.
To build a graph with flot, you’ll need to have a data set available. I just made up a data set in this simple example, but often you’ll pull data from a database or other application. Look over the code first:
This chart was created automatically with a jQuery plugin.
Figure 15-5:
This chart was created automatically with a jQuery plugin.
tmp18764_thumb_thumbtmp18765_thumb_thumb

Here’s the general process:

1. Import the libraries.
It won’t surprise you that you need jQuery. You’ll also need to bring in the jquery.flot script. Note that flot also includes some other scripts, which you’ll need to make available (notably excanvas, which simulates the <canvas> tag on IE browsers).
2. Build your page.
As usual, the page doesn’t require a lot. Just add an empty div that will become your chart.
3. Generate the data.
The data sets in flot are jQuery objects. Each object must have some data, but it can also have other attributes.
4. Note that the data itself is a 2D array.
Each data point is an array of two integers, and the data set is an array of these objects.
5. You can also specify the color and other attributes for the data.
See the flot documentation for many more attributes you can modify.
6. Use the $.plot() function to draw the graph.
Note that the syntax is not exactly what you’ve used before. Use the jQuery $.plot() function to draw a plot on a particular jQuery node.
7. Add as many data sets as you want.
My example has only one data set, but the plot() function expects an array of data ranges, so you can add more if you wish.
As you might guess, the flot plugin features many more incredible effects.

Tag Cloud

In recent years it has become popular to offer data visualizations, or ways to illustrate data. One such mechanism is the tag cloud. Essentially this tool places a number of words in semi-random positions. In a typical tag cloud, the position, size, and color of the words are used to represent the relative strength and relationship of the terms. See Figure 15-6 for a simple example of a tag cloud. Here the text was originally in an unordered list. The tag cloud changes the size and darkness of each element based on a ranking value.
This tag cloud features the main topics of this topic.
Figure 15-6:
This tag cloud features the main topics of this topic.
The jquery tagcloud plugin (http://code.google.com/p/jquery-tagcloud/) makes it quite easy to build your own basic tag clouds. Here’s the code:
tmp18767_thumbtmp18768_thumb

A tag cloud is a pretty fun element to build:

1. Import the libraries.
You’ll need the jquery and jquery.tagcloud scripts.
2. Build a list.
The tagcloud library works on ordered lists and unordered lists.
3. Add numeric values to list items if you wish.
If you want the elements to have different weights, add a value attribute to each. Those with small values will be very lightly colored and show up in a very small font size. Larger values will be darker colors and have larger fonts.
4. Add the tagcloud() function to the ul with jQuery.
Use the standard mechanism to transform the jQuery node based on the ul into a tag cloud.
Note that the value attribute is not standard XHTML, so your page will no longer validate as strict XHTML. Most of the time, the value will be assigned through JavaScript code. (For example, count the number of times a word appears in a document and use that as the term’s value.) Because primary validation happens before the code executes, you won’t see any validation problems.

Tablesorter

AJAX programs often involve retrieving data, which is frequently displayed in an HTML table. The tablesorter plugin (http://tablesorter.com/ docs/) allows the user to sort a table easily by clicking a heading. The top part of Figure 15-7 shows a standard HTML table. When the user clicks the “first name” header, the table is sorted by first names alphabetically, as shown in the bottom part of Figure 15-7.
Here is a basic table.
Figure 15-7:
Here is a basic table.
Click the “first name” header again to sort by first name in inverse order. The default behavior of the tablesorter plugin allows you to sort by any header field. Here’s the code:
tmp1B52_thumb_thumbtmp1B53_thumb_thumbtmp1B54_thumb_thumb

The process is standard jQuery magic:

1. Import jquery and the jquery.tablesorter scripts.
The tablesorter plugin can also work with the jQuery UI for better-looking tables.
2. Build a table.
The plugin requires that your table headings be surrounded by a <thead></thead> pair and the body be surrounded by <tbody> </tbody>. Otherwise you can build your table however you like.
3. Add tablesorter() to the table’s jQuery node.
In the init() function, just specify the table as a tablesorter node, and you’re ready to go.
The tablesorter plugin has dozens of options that make it a real powerhouse. Check the official documentation at http://tablesorter.com/ docs/.
Note that a form of tablesorter was previously included in the jQuery UI, but now it’s a separate plugin.

Jquery-transtate

The jQuery translate plugin (http://code.google.com/p/jquery-translate/) is an incredibly useful tool for language translation. Take a look at the basic page shown in the top half of Figure 15-8. When the user clicks the paragraph, watch what happens (see the bottom half of Figure 15-8).
The user can change this paragraph from English to Spanish!
Figure 15-8:
The user can change this paragraph from English to Spanish!
The translate plugin connects to the Google language API and automatically translates the text of its node to one of several languages. The code that does the trick looks like this:
tmp1B56_thumb_thumbtmp1B57_thumb_thumb

Considering how powerful this trick can be, it’s almost embarrassingly easy to do:

1. Include the jquery and jquery.translate scripts.
As usual, this program uses jQuery and an additional plugin to perform its magic.
2. Create content to translate.
The translate API can only handle a limited number of characters at a time, so don’t try to translate the entire page in one pass. Instead, send smaller chunks (such as a div or paragraph). In this example, I’m translating only one div.
3. Bind the click event to your elements.
In this example, I want my div to begin in English and switch to Spanish when the user clicks it. I bind the click event to a function called
translate() .
4. The translate() function calls the language API, sending the contents.
You can determine the original language as well as the translated language. Dozens of languages are available. The contents of the div are replaced with translated text.
Machine-generated translation only goes so far. Often the general intent of the message will be discernable, but the translation will not be nearly as reliable as a human translation. The API has a particularly difficult time with colloquialism and technical language.

Droppy

Drop-down menus have become an important usability tool in Web sites. There are hundreds of jQuery plugins to handle this feature. I like droppy (http://onehackoranother.com/projects/jquery/droppy/)because it’s very easy to use.
Figure 15-9 shows a simple version of droppy in action.
The droppy plugin turns a list of links into a nice menu.
Figure 15-9:
The droppy plugin turns a list of links into a nice menu.
Most navigation systems are ultimately nested lists of links. The droppy plugin simply takes an unordered list with a bunch of links (nested as deeply as you want) and turns it into a nicely formatted drop-down menu. Take a look at the code:
tmp1B59_thumb_thumb

The general process should be familiar to you by now, but here it is anyway:

1. Include the necessary scripts.
This plugin requires jquery.js and jquery.droppy.js. It also requires an (included) CSS file called droppy.css.
2. Create an unordered list for navigation.
In your HTML code, place the unordered list where you want the menu to be (typically this will be at the top of your page; droppy creates horizontal menus.)
3. Make each top-level element an anchor.
The droppy plugin uses the anchor <a></a> tags for formatting, so make sure the top-level elements (in my example, the language names) are embedded in anchors. It doesn’t matter where the anchor goes, so set the anchor to link back to the page with the # character.
4. Make each interior element a link as well.
Typically the interior elements will be links to other places in your system (or external pages). In my example, I made them empty links, but the important thing is that they contain link elements.
5. Be sure your lists validate.
If you’re sloppy with your nested lists, the plugin will have a hard time figuring out what you’re trying to accomplish, and will probably fail.
6. Build another level of menus if you like.
You can build the navigation structure as deep as you want.
7. Modify the CSS for customization.
You can change the droppy.css file to make the menus fit your needs more closely. The most common changes are colors and fonts, to fit the overall look of the site where the menu will be installed.

Galleria

Image galleries are another very popular plugin topic. There are many image galleries available to play with. I’m demonstrating galleria (http:// devkick.com/lab/galleria/) because it’s popular, powerful, and doesn’t require any server-side scripting. Figure 15-10 shows this beautiful tool in action.
The galleria plugin automatically turns a list of images into a gallery.
Figure 15-10:
The galleria plugin automatically turns a list of images into a gallery.

The default image gallery has some great features:

Images are pre-loaded. Each image is loaded into memory when the page initializes, so there will be no delay when the user switches between images.
The galleria tool automatically creates thumbnail images. The smaller index (thumbnail) images are automatically created and added to the page.
Clicking a thumbnail expands it into the viewing area. The larger viewing area contains a larger version of the current image.
Click the viewing area to view the next image. The default behavior lets you easily cycle through images with mouse clicks.
The output is based on CSS. Use the included CSS file to manage the display of your page, including how and where the thumbnails go, how large the display image is, and more.
It has many options. The galleria plugin is very customizable. It features many advanced options. Check the documentation for more.

My favorite part of the galleria plugin is how easy it is to use. Take a look at the code:

tmp1B511_thumb_thumb
Using galleria is much like any other jQuery plugin. Add the appropriate scripts, write some basic HTML, and add a magical jQuery node:
1. Import the scripts.
You’ll need jquery as always, as well as jquery.galleria and the galleria.css CSS stylesheet.
2. Create a list of images.
Make each list item an image.
3. Add the galleria() node to the list. That’s really all you need to do!
4. Play with the options.
Look over the documentation for some great options, including the ability to use custom thumbnails, specify your own output container, and run callback functions when the user selects an image or thumbnail.

Jmp3

The Web has become a phenomenal multimedia experience, but some important tools are missing. HTML 5 promises (at long last) an audio tag that will allow you to add audio directly to Web pages. Integrating audio (and other multimedia elements) into Web pages has been very complex so far. Most pages use some sort of plugin technology (such as Flash or various media players). The jmp3 plugin (www.sean-o.com/jquery/jmp3/) is a wonderful compromise. It uses a very small Flash component (pre-built — you don’t need to know anything about Flash) to load an audio file you specify and place that file in your page.
Figure 15-11 illustrates a page with an mp3 file embedded in it.
The mp3 files are actually played by a small Flash program, which you can configure in a number of ways — setting the colors and width, and determining whether the player includes a Download button. Take a look at the code to see how it works:
This page has an attractive and functional MP3 player.
Figure 15-11:
This page has an attractive and functional MP3 player.
tmp1B513_thumbtmp1B514_thumb

Using jmp3 follows a familiar pattern:

1. Include the necessary files.
jmp3 uses jquery and jquery.jmp3. It also requires the (included) singlemp3player.swf file be available in the working directory. It’s easiest if the mp3 files are also in the current directory, but not absolutely necessary.
2. Create elements containing the file name.
The plugin uses the text of the element to determine the song file. The node can contain nothing except the filename of the mp3 file. Be sure to use appropriate capitalization.
3. Apply the jmp3() method to appropriate elements.
Apply the jmp3() method to jquery nodes that contain the mp3 file. (It’s perfectly feasible to apply this method to an entire class, as the filename is determined by the contents of the element rather than a jquery parameter.)
4. Add any parameters you prefer.
You can add parameters by attaching a JSON object to the jmp3() call.
5. Change colors.
You can specify foreground and background colors (but note the non-standard color syntax: forecolor instead of color, and no # symbol on color numbers).
6. Set the width.
You can also determine the width of the Flash element. Non-default widths will also include a small scrubber so the user can find a particular part of the song.
7. Specify a file path.
The filepath parameter allows you to link to a file on a remote server. Be sure you have the permission of the file owner to do this. When the user plays the file, the Flash player will begin a progressive download of the file and begin playing as soon as a sufficient fraction of the file is available.
8. Allow downloads.
The showdownload feature allows you to add a small widget to the Flash player. If the user clicks this button, she is given the option to save the mp3 file.
As always, ensure you have the rights to distribute the file before using this option.

Next post:

Previous post: