Published: 25 Feb 2009
By: Xun Ding
Download Sample Code

A step by step example of creating a jQuery plugin and close examination of jQuery UI interaction plugins.

Contents [hide]

Introduction

The indisputable quick rise of jQuery among a large school of JavaScript libraries relies on a few factors:

  1. A light-weight core library, its ability to “write less, do more”;
  2. Strong community support;
  3. Sizable and fast-growing repertoire of plug-ins.

In this article, first we take a look at how to create jQuery plugins and then the official jQuery interaction plugins in jQuery UI library.

How to create jQuery plugins

Before we dive into details, let’s look at some of the general guidelines for writing jQuery plugins.

Naming jQuery plugin files

Generally we name the plug in file in the following fashion:

jQuery.plugin.js

That is, prefix the file name with jQuery, conclude it with .js extension, and put the real plugin name in the middle, so a watermark jQuery plugin will have the following file name: jQuery.watermark.js

Methods and functions

In jQuery, there are two different types of plugins: methods and functions. Methods directly operate on DOM elements and are attached to the jQuery.fn object. For example,

Listing 1: A dummy jQuery plugin

On the other hand, functions are utilities that operate not on DOM elements, but on strings, numbers and other data types. They are attached to jQuery object. For example, the following is a dummy function to change all numbers to percentages:

Listing 2: A dummy jQuery function

From the above two dummy plugins, we can also see some other general principles (as listed by the jQuery team: http://docs.jquery.com/Plugins/Authoring):

  • 'this' is a reference to the current jQuery object.
  • Any methods or functions you attach must have a semicolon (;) at the end
  • methods must return the jQuery object, unless explicitly noted otherwise.
  • Use this.each to iterate over the current set of matched elements

Packaging complex parameters

We all have seen functions / methods with interminable list of parameters. Even worse, users are forced to supply values for those parameters when they are clueless about. In jQuery, the way to avoid this is to use the $.extend() function, and set all parameters as optional while setting their default values. As in the following code:

Listing 3: jQuery extend function to make parameters manageable

Time to create a simple plugin

The web is a never-ending stream of inflow and outflow of data. Forms of textboxes, radios and checkboxes play a major role. Sometimes we get tired of the boring little square checkboxes, so we want to give them a little make-up. How about using different images for checked and unchecked?

So let’s do it.

Step 1: Set up the template

The first thing is set up an empty shell. Let us create a file named jQuery.prettycheckbox.js, and put the following code in it:

Listing 4: An empty jQuery plugin shell

Step 2: A dummy test

Now, let’s test it to make sure that this do-nothing plugin would at least work with a web page. So we create a test HTML page, add a reference to the jQuery core library file and to the plugin file we just created.

Step 3: Wrap up parameters

Next, we use the jQuery .extend function to wrap all the necessary parameters in the one umbrella options parameter.

Step 4: Define the actual mechanism

To give the square checkbox a makeup, we set out to do three things:

  • Use two images to represent the two states of a checkbox, checked or unchecked;
  • Write event handlers for the images’ mouse click events;
  • Hide the actual checkbox, and change its state upon the mouse click event.

Simple enough, right? And we implement it as the following (Note: I have borrowed part of the code from this jQuery checkbox plugin)

Listing 5: Inside the pretty Checkbox plugin

Step 5: Test it one more time

Now we can test our plugin to see it in action. The following test also iterates through every checkbox to make sure it is checked / unchecked correctly.

Listing 6: Put the checkbox plugin in use

Figure 1: Screenshot of the pretty checkbox plugin at work

Screenshot of the pretty checkbox plugin at 

work

jQuery UI

In this Internet age, we collectively contribute to and share the vast repertoire of knowledge available on the web. No exception with jQuery. In fact, jQuery thrives on the ever-growing developer community which has coded a great number of great plugins. So if you missed to check the available plugins, you miss big.

In web development, RIAs (Rich Internet Applications) are all the rage. The rapid growth and development of AJAX technology and JavaScript have further boosted RIA’s reach and capabilities. It is no wonder that the UI (user interface) is in the center and front of jQuery development. Recently the jQuery team has officially introduced the official UI library to the jQuery family. The UI library includes a wide range of core interaction plugins (such as draggable and droppable), widgets (e.g., accordion) and a theming API. All of them can be downloaded at http://jQueryui.com/ (that also houses a good number of demos, code samples and documentation).

Let’s dive in.

Drag and Drop

The first thing in emulating a desktop application is to enable DOM elements to be dragged and dropped. There is no lack of drag and drop scripts. In jQuery, to make elements draggable, we call the following command:

And you know the options parameter encompasses a great deal of options for you to create draggables of your own flavor.

Some of the most important options are:

helper: specifies the dragging mode, a copy or an object itself. You can also specify a helper function with additional requirements. For example, we call the following to add some css styling to the dragging object:

start, stop and drag are events that would trigger callback functions when the drag operation either starts, stops or is ongoing respectively. All of three take two arguments: the event and an UI object that contains

  • Helper (the current helper object);
  • position (top and left of the helper object at the start of the operation);
  • offset (current position of the helper object).

For example, we can track the position of the moving target by recording its x and y coordinates in two text boxes (x and y).

The counterpart of draggable would undoubtedly be droppable. So as there is draggable(options) command, we have a droppable(options) command.

However droppable has a different set of options in store. They are:

accept: specify which draggables can be dropped in its basket. This can be a jQuery selector object or a function that returns true to specify that a draggable is acceptable.

tolerance: a string value that indicates at which point a draggable may be dropped at the receiving area. Possible values are:

  • touch (the draggable touches the droppable)
  • pointer (the mouse pointer enters the droppable)
  • intersect (the draggable touches the droppable)
  • fit (the draggable completely falls within the droppable area).
  • activeClass: css class applied when the dragging process start
  • hoverClass: css class applied when mouse over the drop zone

There are five events with regards to a droppable object:

  • activate (when a potential dragging operation starts)
  • deactivate (when the dragged thing is dropped)
  • over (an accepted draggable is dragged 'over')
  • out (when the acceptable dragging objects is dragged out the zone)
  • drop

All of the above events fire callbacks functions that receive two arguments: the event itself and a ui object. The ui object is furnished with the following properties:

  • draggable - current draggable element, a jQuery object.
  • helper - current draggable helper, a jQuery object
  • position - current position of the draggable helper { top: , left: }
  • offset - current absolute position of the draggable helper { top: , left: }

Putting it together

Now we are able to put together a sample page of jQuery drag and drop.

Listing 7: Sample use of jQuery Drag and Drop

Sortable

Sorting is a common task. And it is fun if users can do it hands-on, drag and drop items around to sort. For example you can drag pictures around to rearrange your photo albums, or adjust your page layout preference by dragging and dropping a panel of items.

Using jQuery sortable is easy and there are a number of configurable options. The obvious ones are cursor, opacity, z-index, handle, revert (if set to true, the item will be reverted to its new DOM position with a smooth animation). For example, we can add a little spice to a little sortable list as such:

Other interesting options about jQuery sortable are:

Placeholder: We can pass a CSS class to the placeholder option of sortable to help users to have a better visual grasp of the items moving around. We can also define the forcePlaceholderSize option to set dimensions on it.

So we go back to our list to add a placeholder option,

Then specify the CSS style for the placeholder class:

connectWith: this allows us to drag and drop items within and among groups. Normally we can set a group of items with the same css class, and pass its name to the connectWith option.

The following is an example how we might order and reorder groups of div element horizontally and vertically by dragging and dropping items (modified from a jQuery sortable demo available at: http://interface.eyecon.ro/demos/sort.html).

Listing 8: jQuery sortable example: the html mark-up

So in the above example, we wrap items in different groups, assign the same CSS class groupWrapper to all of them, then pass the groupWrapper name to the connectWith option. Now users are free to shift items in and out of different groups.

Figure 2: jQuery sortable: enable user to sort among different groups using connectWith

jQuery sortable: 

enable user to sort among different groups using connectWith

jQuery sortable has a number of events defined: start, sort, change, beforeStop, stop, update, receive, remove, over, out, activate and deactivate. All of the events happen and are handled on the client side, so it would be ideal that whenever a list is reordered, we have an easy way to get the new order and pass the information to the server to keep track. Luckily, with sortable we do have a couple of methods at disposal. They are serialize and toArray. Serialize concatenates the sortable's item id's into a form/ajax submittable string; toArray serializes the sortable's item id's into an array of string.

Listing 9: An example of how to use toArray upon a list has been sorted and items positions are rearranged.

Selectable

With jQuery selectable, we can use mouse to draw a box over a group of items to have items highlighted and selected. Just the way we drag our mouse over our desktop and see our folders, icons and files turn blue.

selectable is a little simple plugin, and so is its usage.

For example we have a list with id as selectable. We call upon the jQuery selectable command as such

There are a few options that allow us to fine tune and stylize our selectable, such as delay (time delay in milliseconds before selection can happen), distance (distance in pixels between the selectable and mouse that selection can be initiated).

Resizable

The last plugin in the official jQuery UI interaction category is resizable which enable us to resize an element by holding down on a resize handle.

This is resizable in its very basics:

There are a good set of options to make resizing option animated (animate, animateDuration, animateErasing), constrained (aspectRatio, containment, maxHeight, minHeight, maxWidth, minWidth), delayed (delay), regulated (distance), with more visual feedback (ghost, helper, handle) and synchronized (alsoResize).

So a little advanced resizable plugin usage would be as the following:

Summary

With so much said and done, the craze for jQuery is still on-going and will be likely for a very long time. The power of jQuery lies as much in its core library as its mushrooming plugins. The jQuery plugin reportoire is an inexhautable magical tool box. In this article we go on a brief tour on a: how to create a plugin ourselves, especially, how to create a nifty customizable checkbox; b. the officially-designated gems of jQuery ui library dealing with mouse interactions. Needless to say, the author has borrowed a great deal from what other people have said and coded before, and sometimes may have even forgotten the source of benefactors. If that happens, thanks and sorry.

Happy jQuery plugging in!

References

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Xun Ding

Web developer, Data Analyst, GIS Programmer

This author has published 12 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using asp.net ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
Test120Jan
This is my custom article
Top
 
 
 

Discussion


Subject Author Date
placeholder Awesome article Sonu Kapoor 2/25/2009 8:18 AM
thanks Xun Ding 2/25/2009 10:36 AM
placeholder Excellent article Ralph De Ruijter 2/26/2009 5:29 AM
Good catch Xun Ding 2/26/2009 4:48 PM

Please login to rate or to leave a comment.