How to Author a *simple* jQuery plugin

I use jQuery as the JavaScript library for most projects. It’s terribly convenient for selecting elements and processing them.

However, jQuery is not JavaScript, and there is a lot of things it cannot do. Rather than writing a separate set of functionality outside of jQuery, why not simply extend it on an application-per-application basis? It really is that easy. Perhaps if you get some functionality that is good enough, you will want to convert them into a formal plugin and post it to http://plugins.jquery.com/

Here is the document that explains, in depth, how to author plugins.
http://docs.jquery.com/Plugins/Authoring

Here is an example at a very simple plugin that I whipped together while learning about plugins… It’s designed to accept an object of data, and apply it to any of the elements whose name attribute match the key of the data.

jQuery.fn.populate = function(Data) {
   this.each(function() {
      if (this.name in Data)
      {
         switch(this.type)
         {
            case 'text': this.value = Data[this.name]; break;
            case 'checkbox': this.checked = Data[this.name]; break
         }
      }
   });
   return this;
};

To call it… Select all input elements of the #Login form, and populate them with the passed data.

$('#Login :input').populate({ FirstName: 'sammy', LastName: 'jones' });

The .fn attribute of the jQuery object is where you attach new methods. The this member of those functions is set to the current jQuery object. The function must return the current jQuery object (self) unless explicitly stated otherwise.

Iterating through the elements of the current jQuery object should be done with this.each(…).

All in all, it’s very simple, and very powerful to be able to nest custom functionality into the jQuery object within a given application.

Read more at:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s