5 Simple Steps to Develop a jQuery Plugin
1. Create your plugin with custom name
Let say we are creating a plugin call tgs. The following is the sample script for this tgs function.
$.fn.tgs = function() {
// Our plugin implementation goes here
};
After adding “tgsbegin” function to “$.fn” object this function is now available in jQuery namespace and now you can initialize this function as shown below:
$("#someId").tgs( ) ;
2. Target more than one dom elements
During such requirements you can use the jQuery “each” function over as shown below:
$.fn.tgs = function() {
this.each(function() {
// You will get each targeted element here
});
};
Now, if your are using the plugin to target multiple occurrence of a dom element using a class, it can be done as follows:
$(".someClass").tgs();
3. Make the plugin chainable with other jQuery functions
During such requirement just return the results from “tgs” function over which other jQuery functions can be chained, as follows:
$.fn.tgs = function() {
return this.each(function() {
// You will get each targeted element here
// and it will be returned back
});
};
Now you can chain it with other jQuery functions as shown in the following example:
$("#someId").tgs().removeClass("someClass");
4. Make the plugin configurable by passing options
Using jQuery.extend you can merge two objects.
Here we are using this method to merge the passed options with the default options declared. Refer the example below:
$.fn.tgs = function(options) {
var settings = $.extend({
// Below are the default settings.
fontStyle: "bold",
backgroundColor: "yellow"
}, options );
};
In the above script the options will be passed as shown below:
$( "#someId" ).tgs({
fontStyle: "italic",
backgroundColor: "white"
});
The above script will merge the options passed with the default options and the changes will be effective.
You can also pass this option like as below as well by creating a object literal and passing it as option:
var options = {
fontStyle: "italic",
backgroundColor: "White"
};
$("#someId").tgs(options);
You may also want to make the methods and variable inside plugin implementation private and adding the whole plugin in a scope to provide abstraction.
5. Self invoking Function or Closure
Finally, you can make your plugin to have all the above mentioned features by writing it inside a self invoking function or a Closure as follows.
(function($){
$.fn.tgs = function(options) {
var settings = $.extend({
// Below are the default settings.
fontStyle: "bold",
backgroundColor: "yellow"
}, options );
//Plugin implementation goes here as required
//Return something from here as required
};
}(jQuery));