How to Create your Own Jquery Custom plugin using $.fn?

In programming reuse of codes is a best practice. If the similar functionality you are going to use several times in an application it is suggested to create a common function. Modular approach saves programmers time, easy to maintain, debug as well as help to improves performance of application. The above concept in JQuery is called Plugin. In this session let us explore How to Create your Own Jquery Custom plugin.

Example of Jquery Custom plugin

$.fn.bgcolor = function() {
this.css("background-color", "#00FF00");
};
 
$("div").bgcolor();

Refer to the above example here I created a function bgcolor. Inside this function I am updating background color. To implement this after selector you just need to put a dot & the method name. As a advice if you are looking to create your own plugin related to trigonometry calculations, first create a js file with suitable name & there using $.fn add your required functions one by one. This method saves time as well as easy to debug.

Chaining

During development sometimes we required to implement 5 to 6 methods for one selector. In this case return this; statement is useful. To make your plugin more friendly with real world it is better to add return this; statement at the end of your functionalities. Look at the example below to know how Chaining works in JQuery.

$.fn.bgcolor = function() {
this.css("background-color", "#00FF00");
return this;
};
 
$("div").bgcolor().addClass("updateBgColor");

Protecting the $ Alias

$ is a common used variable in JQuery. Some time it conflicts with other libraries. To avoid this while writing your own JQuery plugin keep remember to use like the following example.

(function ( $ ) { $.fn.bgcolor = function() {
this.css("background-color", "#00FF00");
return this;
}; }(jquery));

Minimizing repetition of $.fn in your Plugin

To improve performance of your own plugin it is better to reduce repetition of $.fn as much as you can. Let’s talk about the below example here from you can know how to avoid unwanted $.fn.

(function($) {
$.fn.whileTrue = function() {
// To Do stuffs while True.
};
$.fn.whileFlase = function() {
// To Do stuffs while False.
};
}(jquery));

Compare to above it is more better to use the following.

(function($) {
$.fn.WhileAction = function(action) {
if (action === "True") {
// To Do stuffs while True.
}
if (action === "False") {
// To Do stuffs while False.
}
};
}(jquery));

Use each() Method

While writing your own plugin if you want to do any manipulating with specific elements then prefer to use .each() to loop through the elements. Look at the example below.

$.fn.myPlugin = function() {
return this.each(function() {
// To Do something for each element here.
});
};