How to create a jQuery plugin with methods?

I'm trying to write a jQuery plugin that will provide additional functions/methods to the object that calls it. All the tutorials I read online (have been browsing for the past 2 hours) include, at the most, how to add options, but not additional functions.

Here's what I am looking to do:

//format div to be a message container by calling the plugin for that div


or something along those lines. Here's what it boils down to: I call the plugin, then I call a function associated with that plugin. I can't seem to find a way to do this, and I've seen many plugins do it before.

Here's what I have so far for the plugin:

jQuery.fn.messagePlugin = function() {
  return this.each(function(){

  //i tried to do this, but it does not seem to work
  jQuery.fn.messagePlugin.saySomething = function(message){

How can I achieve something like that?

Thank you!

Update Nov 18, 2013: I've changed the correct answer to that of Hari's following comments and upvotes.

According to the jQuery Plugin Authoring page (, it's best not to muddy up the jQuery and jQuery.fn namespaces. They suggest this method:

(function( $ ){

    var methods = {
        init : function(options) {

        show : function( ) {    },// IS
        hide : function( ) {  },// GOOD
        update : function( content ) {  }// !!!

    $.fn.tooltip = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            // Default to "init"
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  methodOrOptions + ' does not exist on jQuery.tooltip' );

})( jQuery );

Basically you store your functions in an array (scoped to the wrapping function) and check for an entry if the parameter passed is a string, reverting to a default method ("init" here) if the parameter is an object (or null).

Then you can call the methods like so...

$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method
  foo : 'bar'
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

Javascripts "arguments" variable is an array of all the arguments passed so it works with arbitrary lengths of function parameters.

Here's the pattern I have used for creating plugins with additional methods. You would use it like:

$('selector').myplugin( { key: 'value' } );

or, to invoke a method directly,

$('selector').myplugin( 'mymethod1', 'argument' );


;(function($) {

        myplugin: function(options,arg) {
            if (options && typeof(options) == 'object') {
                options = $.extend( {}, $.myplugin.defaults, options );

            // this creates a plugin for each element in
            // the selector or runs the function once per
            // selector.  To have it do so for just the
            // first element (once), return false after
            // creating the plugin to stop the each iteration 
            this.each(function() {
                new $.myplugin(this, options, arg );

    $.myplugin = function( elem, options, arg ) {

        if (options && typeof(options) == 'string') {
           if (options == 'mymethod1') {
               myplugin_method1( arg );
           else if (options == 'mymethod2') {
               myplugin_method2( arg );

        ...normal plugin actions...

        function myplugin_method1(arg)
   method1 with this and arg

        function myplugin_method2(arg)
   method2 with this and arg


    $.myplugin.defaults = {


What about this approach:

jQuery.fn.messagePlugin = function(){
    var selectedObjects = this;
    return {
             saySomething : function(message){
                              return selectedObjects; // Preserve the jQuery chainability 
             anotherAction : function(){
                               return selectedObjects;
// Usage:
$('p').messagePlugin().saySomething('I am a Paragraph').css('color', 'red');

The selected objects are stored in the messagePlugin closure, and that function returns an object that contains the functions associated with the plugin, the in each function you can perform the desired actions to the currently selected objects.

You can test and play with the code here.

Edit: Updated code to preserve the power of the jQuery chainability.

The problem with the currently selected answer is that you're not actually creating a new instance of the custom plugin for every element in the selector like you think you're doing... you're actually only creating a single instance and passing in the selector itself as the scope.

View this fiddle for a deeper explanation.

Instead, you'll need to loop through the selector using jQuery.each and instantiate a new instance of the custom plugin for every element in the selector.

Here's how:

(function($) {

    var CustomPlugin = function($el, options) {

        this._defaults = {
            randomizer: Math.random()

        this._options = $.extend(true, {}, this._defaults, options);

        this.options = function(options) {
            return (options) ?
                $.extend(true, this._options, options) :

        this.move = function() {
            $el.css('margin-left', this._options.randomizer * 100);


    $.fn.customPlugin = function(methodOrOptions) {

        var method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined;

        if (method) {
            var customPlugins = [];

            function getCustomPlugin() {
                var $el          = $(this);
                var customPlugin = $'customPlugin');



            var args    = (arguments.length > 1) ?, 1) : undefined;
            var results = [];

            function applyMethod(index) {
                var customPlugin = customPlugins[index];

                if (!customPlugin) {
                    console.warn('$.customPlugin not instantiated yet');

                if (typeof customPlugin[method] === 'function') {
                    var result = customPlugin[method].apply(customPlugin, args);
                } else {
                    console.warn('Method \'' + method + '\' not defined in $.customPlugin');


            return (results.length > 1) ? results : results[0];
        } else {
            var options = (typeof methodOrOptions === 'object') ? methodOrOptions : undefined;

            function init() {
                var $el          = $(this);
                var customPlugin = new CustomPlugin($el, options);

                $'customPlugin', customPlugin);

            return this.each(init);



And a working fiddle.

You'll notice how in the first fiddle, all divs are always moved to the right the exact same number of pixels. That is because only one options object exists for all elements in the selector.

Using the technique written above, you'll notice that in the second fiddle, each div is not aligned and is randomly moved (excluding the first div as it's randomizer is always set to 1 on line 89). That is because we are now properly instantiating a new custom plugin instance for every element in the selector. Every element has its own options object and is not saved in the selector, but in the instance of the custom plugin itself.

This means that you'll be able to access the methods of the custom plugin instantiated on a specific element in the DOM from new jQuery selectors and aren't forced to cache them, as you would be in the first fiddle.

For example, this would return an array of all options objects using the technique in the second fiddle. It would return undefined in the first.

$('div').customPlugin('options'); // would return an array of all options objects

This is how you would have to access the options object in the first fiddle, and would only return a single object, not an array of them:

var divs = $('div').customPlugin();
divs.customPlugin('options'); // would return a single options object

// would return undefined, since it's not a cached selector

I'd suggest using the technique above, not the one from the currently selected answer.

jQuery has made this a lot easier with the introduction of the Widget Factory.


$.widget( "myNamespace.myPlugin", {

    options: {
        // Default options

    _create: function() {
        // Initialization logic here

    // Create a public method.
    myPublicMethod: function( argument ) {
        // ...

    // Create a private method.
    _myPrivateMethod: function( argument ) {
        // ...



$('#my-element').myPlugin( {defaultValue:10} );

Method calling:

$('#my-element').myPlugin('myPublicMethod', 20);

(This is how the jQuery UI library is built.)

A simpler approach is to use nested functions. Then you can chain them in an object-oriented fashion. Example:

jQuery.fn.MyPlugin = function()
  var _this = this;
  var a = 1;

  jQuery.fn.MyPlugin.DoSomething = function()
    var b = a;
    var c = 2;

    jQuery.fn.MyPlugin.DoSomething.DoEvenMore = function()
      var d = a;
      var e = c;
      var f = 3;
      return _this;

    return _this;

  return this;

And here's how to call it:

var pluginContainer = $("#divSomeContainer");

Be careful though. You cannot call a nested function until it has been created. So you cannot do this:

var pluginContainer = $("#divSomeContainer");

The DoEvenMore function doesn't even exist because the DoSomething function hasn't been run yet which is required to create the DoEvenMore function. For most jQuery plugins, you really are only going to have one level of nested functions and not two as I've shown here.
Just make sure that when you create nested functions that you define these functions at the beginning of their parent function before any other code in the parent function gets executed.

Finally, note that the "this" member is stored in a variable called "_this". For nested functions, you should return "_this" if you need a reference to the instance in the calling client. You cannot just return "this" in the nested function because that will return a reference to the function and not the jQuery instance. Returning a jQuery reference allows you to chain intrinsic jQuery methods on return.

I got it from jQuery Plugin Boilerplate

Also described in jQuery Plugin Boilerplate, reprise

// 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
    //'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
   //'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


     // 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
              //'pluginName').publicMethod(arg1, arg2, ... argn) or
              $(this).data('pluginName', plugin);





Too late but maybe it can help someone one day.

I was in the same situation like, creating a jQuery plugin with some methods, and after reading some articles and some tires I create a jQuery plugin boilerplate (

In addition, I develop with it a plugin to manage tags ( and wrote a two blog posts explaining step by step the creation of a jQuery plugin (

You can do:

(function($) {
  var YourPlugin = function(element, option) {
    var defaults = {
      //default value

    this.option = $.extend({}, defaults, option);
    this.$element = $(element);

  YourPlugin.prototype = {
    init: function() { },
    show: function() { },
    //another functions

  $.fn.yourPlugin = function(option) {
    var arg = arguments,
        options = typeof option == 'object' && option;;
    return this.each(function() {
      var $this = $(this),
          data = $'yourPlugin');

      if (!data) $'yourPlugin', (data = new YourPlugin(this, options)));
      if (typeof option === 'string') {
        if (arg.length > 1) {
          data[option].apply(data,, 1));
        } else {

In this way your plugins object is stored as data value in your element.

//Initialization without option

//Initialization with option
  // your option

// call show method

What about using triggers? Does anyone know any drawback using them? The benefit is that all internal variables are accessible via the triggers, and the code is very simple.

See on jsfiddle.

Example usage

<div id="mydiv">This is the message container...</div>

    var mp = $("#mydiv").messagePlugin();

    // the plugin returns the element it is called on
    mp.trigger("messagePlugin.saySomething", "hello");

    // so defining the mp variable is not needed...


jQuery.fn.messagePlugin = function() {

    return this.each(function() {

        var lastmessage,
            $this = $(this);

        $this.on('messagePlugin.saySomething', function(e, message) {
            lastmessage = message;

        $this.on('messagePlugin.repeatLastMessage', function(e) {

        function saySomething(message) {
            $this.html("<p>" + message + "</p>");

        function repeatLastMessage() {
            $this.append('<p>Last message was: ' + lastmessage + '</p>');



Here I want to suggest steps to create simple plugin with arguments.

(function($) {
  $.fn.myFirstPlugin = function(options) {
    // Default params
    var params = $.extend({
      text     : 'Default Title',
      fontsize : 10,
    }, options);
    return $(this).text(params.text);

$('.cls-title').myFirstPlugin({ text : 'Argument Title' });
<script src=""></script>
<h1 class="cls-title"></h1>

Here, we have added default object called params and set default values of options using extend function. Hence, If we pass blank argument then it will set default values instead otherwise it will set.

Read more: How to Create JQuery plugin

Try this one:

    var methods = {
            "add":function(){console.log("add"); return this;},
            "init":function(){console.log("init"); return this;},
            "sample":function(){console.log("sample"); return this;}

    methods.init(); // you can call any method inside
    return methods;
$.fn.calendar() // caller or 
$.fn.calendar().sample().add().sample() ......; // call methods

Here is my bare-bones version of this. Similar to the ones posted before, you would call like:

$('#myDiv').MessagePlugin({ yourSettings: 'here' })
           .MessagePlugin('saySomething','Hello World!');

-or access the instance directly @ plugin_MessagePlugin

$elem = $('#myDiv').MessagePlugin();
var instance = $'plugin_MessagePlugin');
instance.saySomething('Hello World!');



    function MessagePlugin(element,settings){ // The Plugin
        this.$elem = element;
        this._settings = settings;
        this.settings = $.extend(this._default,settings);

    MessagePlugin.prototype = { // The Plugin prototype
        _default: {
            message: 'Generic message'
        initialize: function(){},
        saySomething: function(message){
            message = message || this._default.message;
            return this.$elem.html(message);

    $.fn.MessagePlugin = function(settings){ // The Plugin call

        var instance ='plugin_MessagePlugin'); // Get instance

        if(instance===undefined){ // Do instantiate if undefined
            settings = settings || {};
  'plugin_MessagePlugin',new MessagePlugin(this,settings));
            return this;

        if($.isFunction(MessagePlugin.prototype[settings])){ // Call method if argument is name of method
            var args =; // Get the arguments as Array
            args.shift(); // Remove first argument (name of method)
            return MessagePlugin.prototype[settings].apply(instance, args); // Call the method

        // Do error handling

        return this;


The following plugin-structure utilizes the jQuery-data()-method to provide a public interface to internal plugin-methods/-settings (while preserving jQuery-chainability):

(function($, window, undefined) { 
  const defaults = {
    elementId   : null,
    shape       : "square",
    color       : "aqua",
    borderWidth : "10px",
    borderColor : "DarkGray"

  $.fn.myPlugin = function(options) {
    // settings, e.g.:  
    var settings = $.extend({}, defaults, options);

    // private methods, e.g.:
    var setBorder = function(color, width) {        
      settings.borderColor = color;
      settings.borderWidth = width;          

    var drawShape = function() {         
      $('#' + settings.elementId).attr('class', settings.shape + " " + "center"); 
      $('#' + settings.elementId).css({
        'background-color': settings.color,
        'border': settings.borderWidth + ' solid ' + settings.borderColor      
      $('#' + settings.elementId).html(settings.color + " " + settings.shape);            

    return this.each(function() { // jQuery chainability     
      // set stuff on ini, e.g.:
      settings.elementId = $(this).attr('id'); 

      // gives us stuff like: 
      //    $("#...").data('myPlugin').myPublicPluginMethod();
      var myPlugin = {
        element: $(this),
        // access private plugin methods, e.g.: 
        setBorder: function(color, width) {        
          setBorder(color, width);
          return this.element; // To ensure jQuery chainability 
        // access plugin settings, e.g.: 
        color: function() {
          return settings.color;
        // access setting "shape" 
        shape: function() {
          return settings.shape;
        // inspect settings 
        inspectSettings: function() {
          msg = "inspecting settings for element '" + settings.elementId + "':";   
          msg += "\n--- shape: '" + settings.shape + "'";
          msg += "\n--- color: '" + settings.color + "'";
          msg += "\n--- border: '" + settings.borderWidth + ' solid ' + settings.borderColor + "'";
          return msg;
        // do stuff on element, e.g.:  
        change: function(shape, color) {        
          settings.shape = shape;
          settings.color = color;
          return this.element; // To ensure jQuery chainability 
      $(this).data("myPlugin", myPlugin);
    }); // return this.each 
  }; // myPlugin

Now you can call internal plugin-methods to access or modify plugin data or the relevant element using this syntax:


As long as you return the current element (this) from inside your implementation of myPublicPluginMethod() jQuery-chainability will be preserved - so the following works:

$("#...").data('myPlugin').myPublicPluginMethod().css("color", "red").html("...."); 

Here are some examples (for details checkout this fiddle):

// initialize plugin on elements, e.g.:
$("#shape1").myPlugin({shape: 'square', color: 'blue', borderColor: 'SteelBlue'});
$("#shape2").myPlugin({shape: 'rectangle', color: 'red', borderColor: '#ff4d4d'});
$("#shape3").myPlugin({shape: 'circle', color: 'green', borderColor: 'LimeGreen'});

// calling plugin methods to read element specific plugin settings:

// calling plugin methods to modify elements, e.g.:
// (OMG! And they are chainable too!) 
$("#shape1").data('myPlugin').change("circle", "green").fadeOut(2000).fadeIn(2000);      
$("#shape1").data('myPlugin').setBorder('LimeGreen', '30px');

$("#shape2").data('myPlugin').change("rectangle", "red"); 
$("#shape2").data('myPlugin').setBorder('#ff4d4d', '40px').css({
  'width': '350px',
  'font-size': '2em' 

$("#shape3").data('myPlugin').change("square", "blue").fadeOut(2000).fadeIn(2000);   
$("#shape3").data('myPlugin').setBorder('SteelBlue', '30px');

// etc. ...     

This can actually be made to work in a "nice" way using defineProperty. Where "nice" means without having to use () to get plugin namespace nor having to pass function name by string.

Compatibility nit: defineProperty doesn't work in ancient browsers such as IE8 and below. Caveat: $, args) won't work, you need to use, args).

function $_color(color)
    return this.css('color', color);

function $_color_blue()
    return this.css('color', 'blue');

Object.defineProperty($.fn, 'color',
    enumerable: true,
    get: function()
        var self = this;

        var ret = function() { return $_color.apply(self, arguments); } = function() { return $_color_blue.apply(self, arguments); }

        return ret;


JSFiddle link

According to jquery standard you can create plugin as follow:

(function($) {

    //methods starts here....
    var methods = {
        init : function(method,options) {
             this.loadKeywords.settings = $.extend({}, this.loadKeywords.defaults, options);
             methods[method].apply( this, arguments, 1 ));
        show : function() {
            //your code here.................
        getData : function() {
           //your code here.................

    } // do not put semi colon here otherwise it will not work in ie7
    //end of methods

    //main plugin function starts here...
    $.fn.loadKeywords = function(options,method) {
        if (methods[method]) {
            return methods[method].apply(this,
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not ecw-Keywords');
    $.fn.loadKeywords.defaults = {
            keyName:     'Messages',
            Options:     '1',
            callback: '',
    $.fn.loadKeywords.settings = {};
    //end of plugin keyword function.


How to call this plugin?

1.$('your element').loadKeywords('show',{'callback':callbackdata,'keyName':'myKey'}); // show() will be called

Reference: link

I think this might help you...

(function ( $ ) {
    $.fn.highlight = function( options ) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#000",
            backgroundColor: "yellow"
        }, options );
        // Highlight the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
}( jQuery ));

In the above example i had created a simple jquery highlight plugin.I had shared an article in which i had discussed about How to Create Your Own jQuery Plugin from Basic to Advance. I think you should check it out...

Following is a small plug-in to have warning method for debugging purpose. Keep this code in jquery.debug.js file: JS:

jQuery.fn.warning = function() {
   return this.each(function() {
      alert('Tag Name:"' + $(this).prop("tagName") + '".');


      <title>The jQuery Example</title>

      <script type = "text/javascript" 
         src = ""></script>

      <script src = "jquery.debug.js" type = "text/javascript"></script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {

      <p>This is paragraph</p>
      <div>This is division</div>


Here is how I do it:

(function ( $ ) {

$.fn.gridview = function( options ) {


    var factory = new htmlFactory();



}( jQuery ));

var htmlFactory = function(){

     this.header = function(object){

What you did is basically extending jQuery.fn.messagePlugin object by new method. Which is useful but not in your case.

You have to do is using this technique

function methodA(args){ this // refers to object... }
function saySomething(message){ this.html(message);  to first function }

jQuery.fn.messagePlugin = function(opts) {
  if(opts=='saySomething'), arguments[0]); // arguments is an array of passed parameters
  return this.each(function(){


But you can accomplish what you want I mean there is a way to do $("#mydiv").messagePlugin().saySomething("hello"); My friend he started writing about lugins and how to extend them with your chainf of functionalities here is the link to his blog