Click here to Skip to main content
13,836,661 members
Click here to Skip to main content
Add your own
alternative version


89 bookmarked
Posted 28 Nov 2011
Licenced CPOL

How To Write Plugin in jQuery

, 28 Nov 2011
Rate this:
Please Sign up or sign in to vote.
This article provides a comprehensive knowledge to create a plugin.


Apart from offering a simple, effective way to manage elements and various scripts, jQuery also offers a mechanism for adding methods and extra functionalities to the core module. By using this mechanism, we are also allowed to create a new portion of the code and add reuse it in different pages and projects.

Write Your First jQuery Plugin

To write a plugin, add a new property in the jQuery.fn object where the name of the property will be the name of your plugin.

(function( $ ) {
  $.fn.myPlugin = function() {
    // Do your awesome plugin stuff here

})( jQuery );    

Let's start adding functionality within your plugin and use it in web pages. In our first example, I will simply fadeout the element.

(function ($) {

    $.fn.myPlugin = function () {       



Now save the file with name “jquery-myPlugin.js” and your plugin is ready to use. Create HTML button and div on your page. Div will fade out on the click of the button.

Plugin for Multiple Elements

You can also write plugin which performs action on the group of element. Suppose we want to change the background color of the element on mouse over. Simply get each element and register hover event for that object. Let’s start the code for hover plugin.

(function ($) {
    $.fn.hoverElement = function () {
        this.each(function () {
                            function () {
                            function () {
                        ); // end of Hover event

        }); // end for each
    }; // end of functions


$(selector).each() method is used to iterate over a jQuery object, array or any collection. This example registers the hover event for the each element of jQuery object.


The beauty of the jQuery’s design is, it maintains chainability. You can perform multiple actions in one series. So to maintain the chainability in a plugin, you must make sure your plugin returns the ‘this’ keyword.

(function ($) {
   $.fn.hoverElement = function () {
     return  this.each(function () {

                           function () {
                           function () {
                       ); // end of Hover event

       }); // end for each
   }; // end of functions


Now you can perform multiple actions in one series.



If you want to commercialize your plugin, then it should be configurable. For example, we should provide provision to change images, width, height, etc. So users can change the look and feel as per requirement.

For explaining the concept, this example will allow a user to change text, foreground color and background on hover. User can customize the setting as he wants. Now our plugin method will have one argument and the user can pass setting while calling method. See the code below for how the method will look like now.

$.fn.YouPlugin = function (options) {...}

We also need to have default setting object, which will contain default value.

var defaultVal = {
    Text: 'Your mouse is over',
    ForeColor: 'red',
    BackColor: 'gray'

At that time, we have two different objects, one is passed by user and the second has default value. We will merge these two objects using extend method provided by jQuery.

var obj = $.extend(defaultVal, options);

extend() method merges the contents of two or more objects together into the first object. After merging two objects, we will have one final object, which will be used for setting. The complete code of the plugin is below:

(function ($) {

    $.fn.textHover = function (options) {

        var defaultVal = {

            Text: 'Your mouse is over',
            ForeColor: 'red',
            BackColor: 'gray'

        var obj = $.extend(defaultVal, options);

        return this.each(function () {

            var selObject = $(this);

            var oldText = selObject.text();
            var oldBgColor = selObject.css("background-color");
            var oldColor = selObject.css("color");

            selObject.hover(function () {

                selObject.css("background-color", obj.BackColor);
                selObject.css("color", obj.ForeColor);
            function () {
                selObject.css("background-color", oldBgColor);
                selObject.css("color", oldColor);

Advance Image Gallery

We are going to create a plugin which is really close to the Lightbox plugin. Lightbox is a very famous image plugin.

Basically, when an image is displayed on the page, a very handy possibility is offered to the user. Clicking on the (small) thumbnail will cause the image to get bigger and bigger until it reaches its original dimensions and is visible at full size on the very same page that the smaller one's found!

<div id="myGallery">
           <a href="Images/Nature/apple.jpg" title='The apple is the pomaceous...' />
               <img src="Images/Nature/apple_thumb.jpg" />

Get all the anchor (<a>) elements and pass them to the plugin.

$(document).ready(function () {
       $("#myGallery a").imageGallery2();

The plugin gets the collection and registers the click event of each element and on the click event, it adds some elements in the page. After adding, it sets image source, animations and register events on these elements.

$('Body').append("<div id='imageGallery2-overlay'></div>" +
                  "<div id='imageGallery2-wrapper'>" +
                      "<div id='imageGallery2-image-container'>" +
                              "<div id='imageGallery2-close-bar'>
                                  <div id='imageGallery2-close-button'>
                                       <img src='Images/close-icon.png'/>
                              </div>" +
                              "<div style='clear: left; '>" +
                              "<div id='imageGallery2-loadingImage'>" +
                                  "<img  src='Images/loading.gif' 

                width='50' height='50'/>" +
                              "</div>" +
                              "<img id='imageGallery2-image'/>" +
                          "</div>" +

                          "</div>" +
                          "<div id='imageGallery2-image-text-box'>" +
                              "<div id='imageGallery2-image-caption'>" +
                              "</div>" +
                          "</div>" +

As you can see in the example, we preload full image before displaying it. First, we create an image object and register the onload method of the image object. Then we get the source of image from clicked object and assign image source to the image object.

// preload image before displaying
var objImagePreloader = new Image();

var url = objClick.getAttribute('href');

imageCaption = objClick.getAttribute('title');

objImagePreloader.onload = function () {

    $('#imageGallery2-image').attr('src', url);
    // Performance an effect in the image container resizing it
    resizeImageContainer(objImagePreloader.width, objImagePreloader.height);

    //    clear onLoad, IE behaves erratically with animated gifs otherwise
    objImagePreloader.onload = function () { };
objImagePreloader.src = url;

When onload method calls after loading the image, we set source of <img> and set width, height of the container and animated via width and height. User can close opened image by clicking on image itself or by close button. On close, we simply hide caption of the image first and after that, start animation to 0 width and height. On the completion of animation, we simply remove the object from the page and on the click of next image, we simply add them again.

function CloseSelectedImage() {

            ({ width: 0, height: 0 }, 300, function () { 


  • 28th November, 2011: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Shakeel Iqbal
Software Developer (Senior) TEO
Pakistan Pakistan
Passion and positive dedication is essential part of success. I believe on hardworking and sharing knowledge with others. I always try to be a better than I am and think positive for positive result.

My Blogs

My Linked-In Profile

You may also be interested in...

Comments and Discussions

Generalgood Pin
Mohsin Azam24-Dec-13 21:06
memberMohsin Azam24-Dec-13 21:06 
QuestionGetting Error Pin
Sarathkumar Nallathamby6-Mar-13 20:42
professionalSarathkumar Nallathamby6-Mar-13 20:42 
AnswerRe: Getting Error Pin
Shakeel Iqbal8-Mar-13 3:44
memberShakeel Iqbal8-Mar-13 3:44 
Questiongood job. Pin
max042312-Feb-13 9:42
membermax042312-Feb-13 9:42 
GeneralMy vote of 4 Pin
msd181112-Jan-13 22:21
membermsd181112-Jan-13 22:21 
Questionsweet & simple Pin
saiprasad230-Dec-12 8:09
membersaiprasad230-Dec-12 8:09 
GeneralMy vote of 5 Pin
Tim Corey22-May-12 14:06
professionalTim Corey22-May-12 14:06 
GeneralMy vote of 5 Pin
Nullpro12-Jan-12 21:05
memberNullpro12-Jan-12 21:05 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen12-Dec-11 23:45
professionalSunasara Imdadhusen12-Dec-11 23:45 
GeneralMy vote of 5 Pin
hoernchenmeister5-Dec-11 21:39
memberhoernchenmeister5-Dec-11 21:39 
GeneralMy vote of 5 Pin
Monjurul Habib3-Dec-11 1:39
professionalMonjurul Habib3-Dec-11 1:39 
GeneralMy vote of 3 Pin
nrutter30-Nov-11 1:29
membernrutter30-Nov-11 1:29 
QuestionMy vote is 5 Pin
mohamad yousef29-Nov-11 21:48
membermohamad yousef29-Nov-11 21:48 
QuestionExcellent Pin
i_islamian29-Nov-11 20:53
memberi_islamian29-Nov-11 20:53 
GeneralMy vote of 5 Pin
HaBiX28-Nov-11 23:59
memberHaBiX28-Nov-11 23:59 
GeneralRe: My vote of 5 Pin
Shakeel Iqbal29-Nov-11 2:15
memberShakeel Iqbal29-Nov-11 2:15 
QuestionNeat, nicely presented Pin
Sacha Barber28-Nov-11 5:07
mvaSacha Barber28-Nov-11 5:07 
AnswerRe: Neat, nicely presented Pin
Shakeel Iqbal29-Nov-11 2:19
memberShakeel Iqbal29-Nov-11 2:19 
GeneralRe: Neat, nicely presented Pin
Sacha Barber29-Nov-11 4:06
mvaSacha Barber29-Nov-11 4:06 
GeneralMy vote of 5 Pin
Kanasz Robert28-Nov-11 3:38
memberKanasz Robert28-Nov-11 3:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190114.1 | Last Updated 28 Nov 2011
Article Copyright 2011 by Shakeel Iqbal
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid