Javascript/JQuery

How to create a Simple jQuery Plugin

jQuery is a javascript library and the purpose of jQuery is to make use javascript easier. No doubt jQuery is the most loved javascript library by developers since its initial release. Its cutting out lot of development time for developers and making their life easy. jQuery is considered as the one of the most innovative work in the field of web technology.

One of the many “Life Making Easy” features of jQuery is its extendability as a plugin. We can extend the functionalities of jQuery by creating a plugin. Here in this tutorial I am going to teach you how to create a simple jQuery plugin by creating a sample plugin. To create a jQuery plugin, you must have knowledge of javascript. So lets begin.

Basically when we create a jQuery plugin we actually create a javascript function using the jQuery library. That function used along with the jQuery selector to perform some action. Suppose we want to create a jQuery that set the font size of an element to 15px, set its color to blue and make its style italic then our plugin will look like as below code:

The above code is a very simple and basic way of creating a jQuery plugin. But we need some modification in above code to make it actually works globally without conflicting it with other javascript libraries like prototype and making its more customizable for user. Lot of javascript libraries use $ symbol as selector. So to protect our plugin from such libraries by using jQuery.noConflict(), we need some protection mechanism for the plugin. Below is the modified code:-

We did three modification in this code:-

  1. We added two lines of codes, first in beginning and second in the end of the code, to protect our plugin from other javascript libraries as mentioned above.
  2. We passed “options” as a parameter in the plugin function and created two variables “default” & “settings” to link “options” parameter with our default parameters. “options” are the collection of parameters passed by user while using the plugin function.
  3. We used “each” function. The purpose of each function is to apply formatting to each element on the page.

You can use the above code using the sample of code as given below:

 

In the next series of the jQuery tutorial I’ll teach you to create a jQuery plugin more than just basic.

About the author

Sujeet Kr Singh