jQuery Plugin Authoring guide

As soon as you start writing your own jQuery plugins, which is highly recommend to organise and reuse your code, you should check out the official jQuery plugin authoring guide. It has evolved quite a lot since it’s creation and documents several patterns found in jQuery plugins by a lot of different authors. It may also help to understand plugin code of other authors.

I added the “Custom Alias” section a few minutes ago, which provides a handy pattern that you can use even without jQuery:

Above was stated that you should not use the $ alias inside your plugin code. This allows users of jQuery and your plugins to change the alias from “$” to something else like “jQ”. That is necessary when working with other libraries or frameworks which make use of the “$” alias.

On the other hand, we can simply define our own alias (and call it “$”) for our plugin code. The trick is to define all plugin code inside a function and execute this function immediatly. The construct looks like this:

(function() {
  // put plugin code here
  var xyz; // xyz is NOT a global variable, it is only visible inside this function
})(); // execute the function immediatly!

The additional parentheses are necessary! You can’t execute an anonymous function without them.

Ok, now to the fun part:

(function($) {
  // plugin code here, use $ as much as you like

We pass “jQuery” to the function and can now use whatever alias for jQuery we like. So instead of $ you could also any other valid javascript variable name.

See the tooltip plugin for a plugin that uses this pattern.