JS: 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 JS: Prototype and Inheritance]

[see JavaScript Prototype: Define Your Own Methods]

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/

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon