in jQuery

Simple jQuery Plugin Example

In this article, I will teach you how to develop a standard jQuery plugin. I will keep things as simple as possible and will only build a very trivial plugin, but through this example I will cover all of the important aspects of jQuery plugin development.

Before we begin, let’s outline exactly what we are going to build.

Covered in this article:

  1. Avoiding JavaScript Library Conflicts
  2. Operating on collections of elements
  3. Preserving Method Chaining
  4. Parametirizing our plugin
  5. Loading our plugin
  6. Calling our plugin
  7. Summary

1. Always Avoid Conflict – Remain Anonymous

It is not uncommon for a web site to use multiple Javascript libraries, for instance jQuery and Prototype. Since several of the popular JavaScript libraries use the $ (dollar sign) namespace, conflicts can occur causing one or all of the libraries to break.

JavaScript provides us with a handy technique for avoiding conflicts: the anonymous function. Wikipedia defines an anonymous function like so:

“In computing, an anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to an identifier.”

This means that the function will not be stored in a variable or otherwise named. The function will receive a single argument, the $ variable. It is important to note that the $ variable inside the function will be unique in the function’s scope and will not conflict with any other variable by the same name. It will also contain a reference to the jQuery object because we will pass the jQuery object to our anonymous function.

/**
 * Create an anonymous function to avoid library conflicts
 */
(function($) {
    // The body of our plugin will go here
})(jQuery);

This may all look and sound confusing but it’s actually very simple. What we have done is identical to this:

var doSomethingKickAss = function($) {
    // Do something
};
doSomethingKickAss(jQuery);

The only difference is that in the first case, we don’t bother with naming the function, thus the term “anonymous”. We simply create and execute the function in a single, efficient step.

Leave a Reply

Webmentions

  • jQuery Plugin to Toggle Default Field Value on Focus and Blur « Technify.me November 14, 2011

    […] jQuery Plugin Tutorial […]