jQuery Plugin Boilerplate

Get the latest updates on this jQuery plugin via RSS
 
Please refer to the new version of the jQuery Plugin Boilerplate
 

A boilerplate for jump-starting jQuery plugins development.

Contains lots of comments to help you get going easily. It implements public and private methods, as well as public and private properties making it the ideal candidate for when building both simple and complex jQuery plugins.

It does not adhere to the suggestions made by the jQuery documentation regarding Plugins/Authoring.

The jQuery Plugin Boilerplate took some inspiration from Doug Neiner‘s Starter.

With comments:

// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 1.1, May 14th, 2011
// by Stefan Gabos

// remember to change every instance of "pluginName" to the name of your plugin!
(function($) {

    // here we go!
    $.pluginName = function(element, options) {

        // plugin's default options
        // this is private property and is  accessible only from inside the plugin
        var defaults = {

            foo: 'bar',

            // if your plugin is event-driven, you may provide callback capabilities
            // for its events. execute these functions before or after events of your
            // plugin, so that users may customize those particular events without
            // changing the plugin's code
            onFoo: function() {}

        }

        // to avoid confusions, use "plugin" to reference the
        // current instance of the object
        var plugin = this;

        // this will hold the merged default, and user-provided options
        // plugin's properties will be available through this object like:
        // plugin.settings.propertyName from inside the plugin or
        // element.data('pluginName').settings.propertyName from outside the plugin,
        // where "element" is the element the plugin is attached to;
        plugin.settings = {}

        var $element = $(element), // reference to the jQuery version of DOM element
             element = element;    // reference to the actual DOM element

        // the "constructor" method that gets called when the object is created
        plugin.init = function() {

            // the plugin's final properties are the merged default and
            // user-provided options (if any)
            plugin.settings = $.extend({}, defaults, options);

            // code goes here

        }

        // public methods
        // these methods can be called like:
        // plugin.methodName(arg1, arg2, ... argn) from inside the plugin or
        // element.data('pluginName').publicMethod(arg1, arg2, ... argn) from outside
        // the plugin, where "element" is the element the plugin is attached to;

        // a public method. for demonstration purposes only - remove it!
        plugin.foo_public_method = function() {

            // code goes here

        }

        // private methods
        // these methods can be called only from inside the plugin like:
        // methodName(arg1, arg2, ... argn)

        // a private method. for demonstration purposes only - remove it!
        var foo_private_method = function() {

            // code goes here

        }

        // fire up the plugin!
        // call the "constructor" method
        plugin.init();

    }

    // add the plugin to the jQuery.fn object
    $.fn.pluginName = function(options) {

        // iterate through the DOM elements we are attaching the plugin to
        return this.each(function() {

            // if plugin has not already been attached to the element
            if (undefined == $(this).data('pluginName')) {

                // create a new instance of the plugin
                // pass the DOM element and the user-provided options as arguments
                var plugin = new $.pluginName(this, options);

                // in the jQuery version of the element
                // store a reference to the plugin object
                // you can later access the plugin and its methods and properties like
                // element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
                // element.data('pluginName').settings.propertyName
                $(this).data('pluginName', plugin);

            }

        });

    }

})(jQuery);

Without comments:

// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 1.1, May 14th, 2011
// by Stefan Gabos

(function($) {

    $.pluginName = function(element, options) {

        var defaults = {
            foo: 'bar',
            onFoo: function() {}
        }

        var plugin = this;

        plugin.settings = {}

        var $element = $(element),
             element = element;

        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);
            // code goes here
        }

        plugin.foo_public_method = function() {
            // code goes here
        }

        var foo_private_method = function() {
            // code goes here
        }

        plugin.init();

    }

    $.fn.pluginName = function(options) {

        return this.each(function() {
            if (undefined == $(this).data('pluginName')) {
                var plugin = new $.pluginName(this, options);
                $(this).data('pluginName', plugin);
            }
        });

    }

})(jQuery);

Usage

$(document).ready(function() {

    // attach the plugin to an element
    $('#element').pluginName({'foo': 'bar'});

    // call a public method
    $('#element').data('pluginName').foo_public_method();

    // get the value of a property
    $('#element').data('pluginName').settings.foo;

});

Top

Requirements

jQuery 1.5.2+

It’s the only version I’ve tested the boilerplate with; it may be applicable to earlier versions, too. If you can test, please let me know. Thanks!

Top

40 responses to “jQuery Plugin Boilerplate”

Follow the comments via RSS
  • ionut, 2011-07-07, 11:17

    Thanks for responding Stefan

    sorry to disturb you further but i’m new at javascript and jquery and i want to be sure i develop the plugin correctly
    can the plugin be called like this

    $('#content').myplugin({
        foo: 'test'
    }, function onFoo(data){
        do something with returned data
    }, function onBoo(data){
        do something
    });
    

    ?

    in the boilerplate you have

    onFoo: function() {}

    is that a function or what ?
    if i call the plugin like i said before is the onFoo called or i need to define the function like in your example

    plugin.onFoo = function(data) { return data; }

    not sure if i got the info correctly i want to define some functions that (return some data or not) in my plugin and let the user call the functions

    if i define a function can the user overwrite the functionality ?
    example i bind a function to be executed onclik how can i let the user define his own code and bypass my function ?

    thanks in advance for any response

    Reply
    • Stefan Gabos, 2011-07-07, 11:40

      you are making a confusion between public methods – methods that can be called from “outside” – and events which are fired by the plugin during different stages and are to be “hooked” from a custom function.

      for the public methods read the comments and the usage examples. let’s say you have a tooltip plugin and in it you may a have a public method named “close” that hides the “tooltip”. you’d use $(‘#element’).data(‘pluginName’).close().

      events are fired by the plugin during different stages and are to be “hooked” from a custom function. for our tooltip plugin we might want to have the “onClose” event. In this case, you’d replace “onFoo” with “onClose” (leave the function(){}) and in our public method called “close”, after all the code runs, we’d call “plugin.onClose()”. this way, if the user attached a custom function to the onClose() event, it will be executed when the tooltip closes.

  • ionut, 2011-07-07, 15:45

    thanks Stefan you have been a great help
    can you recommend some related books that will help me understand this thing better

    Reply
  • srini, 2011-07-28, 15:32

    I tested with jQuery 1.5.1 and it works fine…

    Reply
    • Stefan Gabos, 2011-07-29, 06:07

      thanks!

  • Max, 2011-10-12, 10:45

    Hey Stefan,

    really love your plugin boilerplate and have used it a few times by now.
    I have one question however:

    Is there a specific reason why the init function is public?

    Reply
    • Stefan Gabos, 2011-10-12, 12:02

      no particular reason…you’re right it shouldn’t be public :)

  • Harry, 2011-10-13, 20:54

    I am very confused about using both $.pluginName and $.fn.pluginName. If the plugin will operate on the DOM why not just use the $.fn namespace.

    Also the code inside $.fn.pluginName doesn’t allow calling public methods with strings which is the most recommended way to call plugin methods according to http://docs.jquery.com/Plugins/Authoring

    Reply
  • Fili, 2011-10-25, 11:49

    Thanks for this excellent boilerplate, I use it often. Just out of curiosity; the second variable declaration in line below seems redundant, is that there pure for aesthetics?

    var $element = $(element), element = element;

    (ps. the captcha on this page is quite unreadable)

    Reply
    • Stefan Gabos, 2011-10-25, 11:52

      yes it is there so that both $element and element are visible side by side and users realize that there’s a difference

  • Gustavo Sillero, 2011-11-28, 03:54

    First of all, thanks for your work, it’s very handy :)
    So, I made a few additions suiting my needs, but I would like your opinion on this specific change:

    (function($) {
    	var pluginName = "pluginName";

    $[pluginName] = function(element, options) { ... }

    $.fn[pluginName] = function(options) {

    return this.each(function() { if (undefined == $(this).data(pluginName)) { var plugin = new $[pluginName](this, options); $(this).data(pluginName, plugin); } });

    } })(jQuery);

    this way you don’t need to remember to change every instance of pluginName and it can also be referenced inside for logging and other purposes

    Reply
    • Stefan Gabos, 2011-11-28, 07:46

      the code is perfectly ok I just don’t like how it looks :) but it’s a subjective point of view

    • Gustavo Sillero, 2011-11-29, 21:18

      I perfectly understand your point of view. Thanks for replying.

  • Tom Carnevale, 2011-12-18, 18:06

    Just came across this. Wish I had seen it sooner! Great!!

    Thanks!

    Reply
  • Claire, 2012-01-24, 23:00

    How would you use this to extend an existing plugin? say there is a $.fn.baseplugin you want to extend do you then use $.fn.baseplugin.myoverrides to build the overriding one?

    Reply
  • Falko, 2012-02-09, 11:56

    I made a small modification to ease the access to public methods:

    $.fn.DialogPersonAuswahl = function (options) {
    if (options == undefined && $(this).data(pluginName) != undefined)
    return $(this).data(pluginName);
    else
    return this.each(function () {
    if (undefined == $(this).data(‘DialogPersonAuswahl’)) {
    var plugin = new $.DialogPersonAuswahl(this, options);
    $(this).data(‘DialogPersonAuswahl’, plugin);
    }
    });

    };

    Access methods:
    // first call creates the plugin
    $(‘#element’).pluginName().
    // further calls access the plugins methods
    $(‘#element’).pluginName().foo_public_method();

    Reply
  • paul, 2012-02-22, 19:31

    thanks for this, i read through the jquery docs for this and this is SOOO much easier to understand. thank you.

    Reply

Leave a Reply

Your email address will not be published
You can use <strong>, <em>, <a>, <img>, <code>
Characters are not case-sensitive