Search code examples
jqueryjquery-templates

Shortest and Quickest way to write a jQuery plugin


What is the shortest and quickest way to write a jQuery plugin to have all jQuery functions, methods and available properties, but to avoid this pattern which is in most cases stored in jquery.*-plugin.js files:

(function($){
    $.yourPluginName = function(el, radius, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;

        // Add a reverse reference to the DOM object
        base.$el.data("yourPluginName", base);

        base.init = function(){
            if( typeof( radius ) === "undefined" || radius === null ) radius = "20px";

            base.radius = radius;

            base.options = $.extend({},$.yourPluginName.defaultOptions, options);

            // Put your initialization code here
        };

        // Sample Function, Uncomment to use
        // base.functionName = function(paramaters){
        // 
        // };

        // Run initializer
        base.init();
    };

    $.yourPluginName.defaultOptions = {
        radius: "20px"
    };

    $.fn.yourPluginName = function(radius, options){
        return this.each(function(){
            (new $.yourPluginName(this, radius, options));

           // HAVE YOUR PLUGIN DO STUFF HERE


           // END DOING STUFF

        });
    };

})(jQuery);

I am looking for a quick jQuery plugin pattern/template which I can use in my main.js file where I do all of my JavaScript logics and jQuery things.

What I want to do is to avoid using jquery.*-plugin.js files for some of my custom plugins which will be used only on some sections and portions of my website.


Solution

  • It really depends what functionality you need, but a jQuery plugin is simply a method of jQuery.prototype (which is aliased to jQuery.fn) so you can just do this:

    $.fn.myPlugin = function () {
        // `this` refers to the jQuery instance. Put your logic in here.
    };
    

    You can then call it like this:

    $(".some-selector").myPlugin();
    

    Here's a working example.