jQuery Plugin Template

Posted by Darwin Biler on July 20, 2013

Need to write a jQuery Plugin very quick? copy paste the code below!

;(function ( $, window, document, undefined ) {
    var pluginName = "myplugin", // change your plugin name in here
        //add default values
		defaults = {
            color: "#000" 
        };
    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options );

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype = {

        init: function() {
			// add initialization codes
			$(this.element).css({color:this.options.color});
        },

		//add other functions
        yourOtherFunction: function(el, options) {         
        }
    };

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin( this, options ));
            }
        });
    };

})( jQuery, window, document );

Usage

On line 2, you need to put your own plugin name.
Line 4-6 defines the default options in case the plugin is initialized without any options.
Line 19-22, you can do whatever initialization stuff you need here. The element and option can be accessed by this.element and this.options respectively.
Line 24-26, is just a sample function, you can create as many as this.

You can also download the demo in here

This page is meant to be used for quick access, this doesn't really explain in detail what and how jQuery plugin works. You can go here and here to learn more about jQuery Plugins.


Did you find this useful?

I'm always happy to help! You can show your support and appreciation by Buying me a coffee (I love coffee!).