JavaScript: How to Write a JQuery Plugin

By Xah Lee. Date: . Last updated: .

what's jQuery's $.fn?

It is just a alias to the prototype property. You can see it in the jQuery source code:

jQuery.fn = jQuery.prototype = {
    // …
}

But why we need a alias? Presumably, they aliased so it's shorter to type.

But why is it named “fn”? Perhaps it's because “fn” mean function, and it gives people the right idea of assigning function to it.

[see Prototype and Inheritance]

[see Add Method to Prototype]

How to write a jQuery extension/plugin?

All you have to do is:

$.fn.myNiceExtensionF = function(){}

Your function shoud return a jQuery object (this) when appropriate, so it's chainable.

Actually, you should do this so your extension can have lots properties/methods:

$.fn.myNiceExtensionF = { f1:function(){}, f2:function(){}, // … }

The above is the basic idea, actually more details, see: http://learn.jquery.com/plugins/basic-plugin-creation/

BUY ΣJS JavaScript in Depth