Published: 03 Nov 2008
By: Karl Seguin

Build highly reusable JavaScript components by leveraging JQuery's simple plug-in architecture.

Contents [hide]


In part 1 we looked at two of the three core JQuery abilities: DOM traversal and manipulation. In this part we'll look at the third: extensibility. In fact, one might worry that given JQuery's focus on core functionality, more advanced use might be limited. However, given the raw power of JQuery and its popularity, almost any functionality you could think of is already available as a free plug-in. The JQuery website has a repository for hundreds of contributed plug-ins; as well as the official JQuery UI - which adds rich visual and usability behavior to the core JQuery framework. Occasionally though, you'll need to build your own plug-in; maybe to share with the world, or across projects, or even just to re-use through a single site. Thankfully, JQuery makes it trivially easy to extend on its base capabilities.


Before we build our first plug-in, the JQuery team has a few recommended best-practices for plug-in authors. First, since the JQuery function always returns an array of JQuery objects, our plug-in should apply itself to such an array (instead of an individual item). Second, we should always return the current JQuery object in order to allow our plug-in to be chained with other calls. JQuery makes it very easy to follow these two guidelines by providing an iterator method (each) that we can use. If you plan on releasing this plug-in to the public, you should head over to the official JQuery authoring guide for more detailed guidlines dealing with compatibility and naming.

Numeric Mask Plug-in

For our plug-in, we’ll stick with a simple example: applying a numeric mask. The first thing to do is attach our method, named numeric to the JQuery object:

With this simple code in place, we can attach our function to any JQuery objects:

Of course, our plug-in doesn't do anything yet. Within our function this refers to the array of JQuery objects that were selected. The simplest way to allow for method chaining is to return this:

And the best way to make sure our mask is applied to any number of matched elements is to use the each iterator:

We can merge the two examples to fulfill the 2 core guidelines:

This forms the template to follow for any JQuery plug-in. Now we can start to work on the code specific to our plug-in. The first thing to do is bind to the keydown event:

Within the each function, this has reverted back to the DOM element; therefore to bind to the JQuery keydown event, we turn it into a JQuery object (keeping track of whether this is a DOM element or a JQuery object is, in my opinion, the most difficult aspect of using JQuery).

Finally we can implement functionally working code (albeit rather limited):

Although there’s still a lot to do to make our plug-in acceptable (at the very least we need to support non- character inputs such as arrow keys), let’s focus on more JQuery-specific enhancements. (Incidentally, the second set of allowed key codes (from 96 to 105) is for the numpad).

A very common JQuery pattern is to allow plug-ins to be customized via an options attribute. For now, we’ll add a single option which sets a default value. First the code:

We've made two top-level changes: added support for options, and added a new method to our plug-in. Enabling options required only three straightforward steps:

  1. Define our default options (the last line of code),
  2. Add an options parameter to our numeric function (the first line of code), and
  3. Merge the supplied options (if any) with the default (the third line of code)

The last step uses the jQuery extend utility method. It merges objects together and returns a new one. With those three steps in place, we can use the options within our plug-in to change its behavior. We can specify options by passing them to our numeric plug-in:

The other change that we've made is to add a helpful isControlKey function. The function is added to our numeric namespace so we aren't polluting jQuery's. As such the isControlKey method is publically available and can be used by others or even extended.

What if you don't want isControlKey or some other function to be public? The solution is to wrap your entire plug-in within a closure. Before we go ahead and make that change, take a look at the following code:

It probably seems strange, right? If you look at the grouping of parenthesis you should notice that its really nothing than a function call with a single parameter. Here' what our revised plug-in looks like:

isControlKey is now private. This also means that we don't have to access it via its full name as in the previous example. However, since we've kept the default options plug-in (which is generally a good idea), we still use the full $.fn.numeric.defaults name.

Static Methods

You may want to add a static method to jQuery itself; perhaps like its own extend or inArray methods which we've already used. To do so simply add your method to the jQuery object itself (as opposed to jQuery.fn):

Which can then be called via:

As always, try not to group like-functionality into shared object/namespace:

Which can then be called via:


Hopefully these two articles have provided you with some insight into jQuery as well as peaked your interest for an upcoming project. jQuery makes a number of otherwise complicated things easy to write, read and maintain. We've touched on a good part of what jQuery offers, except that the API has many more available selectors and manipulators than the handful we covered. jQuery also provides AJAX capabilities as well as basic utility functions. Best of all, it's a very well-documented framework with a vibrant community.

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

About Karl Seguin

Karl Seguin is an senior application developer at Fuel Industries, located in Ottawa, Ontario. He's an editor here at DotNetSlackers, a blogger for the influential and a Microsoft MVP.

This author has published 8 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 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...
This is my custom article

You might also be interested in the following related blog posts

CRUD Operations using Partial View and jQueryUI in ASP.NET MVC4 - Part 2 read more
Introducing SharePoint 2010 Training at U2U read more
The Underground at PDC read more
Assembly-Free jQuery in SharePoint Sites Using the SmartTools jQueryLoader read more
My History of Visual Studio (Part 6) read more
BeginDialOut with Office Communicator Clients read more
DotNetNuke Fusion Results for Q3 read more
GiveCamps Get a new Sponsor read more
Announcing the WebsiteSpark Program read more
Scenarios for WS-Passive and OpenID read more


Subject Author Date
placeholder Nice Article Shailendra Singh Chauhan 11/5/2008 3:28 AM
RE: Nice Article Karl Seguin 11/6/2008 6:57 PM
placeholder why numeric plugin not work on Opera? Ming Zhu 11/8/2008 11:49 AM
RE: why numeric plugin not work on Opera? Karl Seguin 11/9/2008 12:32 PM
placeholder RE: why numeric plugin not work on Opera? Ming Zhu 11/10/2008 1:05 PM

Please login to rate or to leave a comment.