PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » jQuery Plugin Template

jQuery Plugin Template

Replace instances of "yourPluginName" with your actual plugin name. The stuff about "radius" is just an example of an option (parameter to pass plugin).

(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);

Usage

$(function() {

    $("#round-me").yourPluginName("20px");

});

Reference URL

Subscribe to The Thread

  1. That’s very useful, thanks!

  2. Another very nice and useful snippet!

    keep up the good work!

  3. Nice template. Quite a different layout from others I’ve seen, but will definitely give this a go.

    Here’s an alternative jQuery plugin template.

    Thanks

  4. Martin

    This template is totally different from jquery docs. Are their any benefits to this type of template format?

  5. I find this template the best out of all the ones I’ve used. It’s been my starting point for the past couple years.

  6. unstoppableCarl

    I don’t completely follow the logic of its organization. I think it would be easier to understand if your example had some event driven functionality.

  7. Peter G

    How would you go about making functions public with this template?

    e.g. access a function called base.foo?

    Cheers!

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~