Simple jQuery Plugin Working Example

I recently started developing a jQuery plugin for a project.  I found jQuery plugin development to be very interesting and can see many areas where I can use plugins going forward.

One of the best overviews of plugins I have found was over at WebDevEasy.  The author discusses plugins that work on an element and plugins that do not.  

After writing a couple of jQuery plugins that were meant to handle processing vs. elements, I decided to post this template for myself for future use. 

First the Plugin Code:  The following code has one Public and one Private function. This plugin is not meant to work on an element but meant to handle the processing required by calling a public method.  

The function starts with a semi-colon before (function ($) as a way to protect this plugin if another developer did not end their plugin with a semi colon. 
;(function ($) {
        
    //----------------------------------------
    // Create Plugin
    //----------------------------------------
    $.myPlugin = function (param1, param2) {

        //-------------------
        // Public Functions
        //-------------------       
        return {
            //---------------------
            // Public functions
            //----------------------
            myPublicFunction: function (param1) {
                myPrivateFunction(param1);
            },
        };
    };
    //End Plugin ----------------------

    //===========================================
    //===========================================
    // Private Functions 
    //===========================================
    //===========================================
    function myPrivateFunction(param1)
    {
        console.log('myPrivateFunction(): ' + param1);
    }

})(jQuery);

Plugin Use:  The following button click event calls a function which in turns calls a public method of the plugin.
<button onclick="pluginTest();">Test Plugin</button>
Get an instance of the plugin and call myPublicFunction()
function pluginTest() {
    var myTestPlugin = $.myPlugin('This is Param 1', 'This is Param 2');
    myTestPlugin.myPublicFunction('This is Param 1');
}

Results from the console:
myPrivateFunction(): This is Param 1
Comments are closed