Introduction
Creating a plugin in Jquery is very easy. Before creating a plugin, we need to know the basic naming convention that will be used in plugins. The common and most popular naming convention is Jquery.pluginName.js or Jquery.pluginName.versionNumber.js. Using the version in plugin avoids adding wrong version of plugins. If it is a minified file, try to add .min before .js extension. If you want to publish your plugin publicly, then make sure that plugin name is not taken already by somebody else.
The basic structure of a plugin is very simple. It looks like the below script:
(function($){
$.fn.pluginName = function(){
return this;
};
})(jQuery);
In the above code, we have used one anonymous function which takes jQuery as a parameter. This function will be called as soon as DOM is loaded. Any plugin may need some parameters which will be passed by the user while initializing. If it requires two or three parameters, then we can directly define in the plugin function. But if the plugin requires multiple parameters or has some default values, then we cannot use direct parameters. Here we need to use Json object as a parameter.
(function($){
$.fn.pluginName = function(options){
var defaultOptions = {parameter1:'value 1', parameter2:'value2'};
var finalOptions=[];
$.extend(finalOptions, defaults, options);
return true;
};
})(jQuery);
In the above code, we have defined some default values to the parameters. It means if the user does not pass any parameters, then default parameters will be used. If the user passes any parameters, then they will be taken and will be merged with finalOptions
. For this, we have used extend function. Now, I will use a simple example to explain the plugin better. You see demo here to better understand how to create jquery plugins. Let's say I want to create a plugin to change the background color. Then, my plug in code will be as below:
(function($){
$.fn.testPluin = function(options){
var defaultOptions = {backColor:'yellow' };
var finalOptions=[];
$.extend(finalOptions, defaults, options);
return this.css('background': finalOptions.backColor);
};
})(jQuery);
$("div").testPluin({backColor: 'red'});
<div> This is simple plugin </div>
Here, we are passing red color while initializing. So the div
gets red background color. If we do not pass any parameter, then default color will be used that is yellow.