How to create a jQuery plugin

Programming


There are is huge amount of jQuery plugins for almost every purpose. However, sometimes the developer needs a certain special script for his project. I also was in such a situation several times, so now I’d like to share with you my personal tips (and, hopefully, best practices).

1) Create self-invoke anonymous function to fire scripts when it’s loaded:

(function($,window,){
})(jQuery,window)

We pass in $, window, and . The arguments of the self-invoking function are also called with the jQuery and window; for  nothing is passed in. Thus if we decide to use the keyword within the plugin, “” actually will be .

$ is passed as jQuery; we do it this way to ensure that outside of the anonymous function $ can still refer to something else only, such as Prototype or Mootools.
Passing the globally accessible window variable allows you to compress the code through the minification processes (which you should be doing, as well).

2) Create a jQuery function inside of it using $.fn method:

(function($,window,){
   $.fn.myplugin = function(){
     };
})(jQuery,window)

Now you can fire your script in such a simple way:
Example:

$('#someId').myplugin();

3) Next step is just my own tip

I always create an object with methods and fire init() method at the end of the script.
Example:

(function($,window,){
$.fn.myplugin = function(){
var myObj = {
init : function(){
console.log(‘Your plugin is inited’);
},
//some methods:
render : function(){
}
}
myObj.init();
};
})(jQuery,window)

4) Now we will create some simple functionality

Let’s display an unordered list of items in a render function:

render : function(){
var items = ['Apple', 'Samsung', 'HTC', 'Nokia', 'LG'];
arrLen = items.length,
cont = '';

var content = $('<ul/>,{
    class : 'ul-class'
    });

    for (var i=0; i < arrLen ; i++){
    cont+= '<li>' + items[i]+ '</li>';
    }

    content.html(cont);

    myObj.wrapper.append(content);
    }

    5) To make your plugin more flexible, you can create configuration, using $.extend function

    First create a configuration object, like this one:

    var config = {
           items : ['Apple', 'Samsung', 'HTC', 'Nokia', 'LG'],
           ulClass : 'ul-class'
    };

    Then add the ability to pass options to the plugin and merge them.

    Example of initial function:
    init : function(){ this.wrapper = $('#wrapper'); this.config = $.extend({}, config, options); this.render(); }

    All options will be used from the merged configuration.
    Code listing:

    Html:

    <DOCTYPE html>
           <meta charset='utf8'>
    <html>
           <head><title>Test plugin</title>
           </head>
           <body>
                    <div id='wrapper'>
            
                    </div>
           </body>
    </html>

    JS:

    (function($,window,){
       $.fn.myplugin = function(options){
           var config = {
               items : ['Apple', 'Samsung', 'HTC', 'Nokia', 'LG'],
               ulClass : 'ul-class'

          };

           var myObj = {
               init : function(){
    this.config = $.extend({}, config, options);
                   this.wrapper = $('#wrapper');
                   this.render();
              },
               //some methods:
               render : function(){
                  var items = myObj.config.items;
                       arrLen = items.length,
                       cont = '';

                   var content = $('<ul/>',{
                       class : myObj.config.ulClass
                   });

                  for (var i=0; i < arrLen ; i++){
                       cont+= '<li>' + items[i] + '</li>;
    }

                  content.html(cont);

                   myObj.wrapper.append(content);
           }
         };
           myObj.init();
    };
    })(jQuery,window)

    $.fn.myplugin({
             items : ['Nexus','Ipad'],
             ulClass : 'mytestclass'

    });

    This is just one simple example of a jQuery plugin, but it can give you a basic understanding of how to create flexible jQuery plugins.

    web development company chicago

    Live example: http://jsfiddle.net/nkKYW/1/

    See also: Semantics in HTML5

    Comments