How to create a jquery plugin

Let us create a simple “jquery circle plugin”.

create a div in your index page, this is our div element which animates later as a circle!

<div id="circular" class="_default_circle"> plugin</div>

The important ones are the CSS:

._default_circle{ 
  width:50px;
  height:50px;
  background:#00FFFF;
  border:#0000FF solid 1px; text-align:center;
}

._custom_circle{
  width:50px;
  height:50px;
  background:#00FFFF;
  border:#0000FF solid 5px;
  text-align:center; top:50%;
  -webkit-border-radius: 999px;
  -moz-border-radius: 999px;
  border-radius: 999px;
  behavior: url(PIE.htc);
}

The ._default_circle is used for the div on the initial load, the ._custom_circle is used when you actually access the div through your plugin.

Jquery plugin structure explained!

We can initiate the actual function of the plugin using the jQuery built-in structure

Now, for the creation of a function

inside the extended function write something like this

(function($){....... })(jQuery);Next, make sure that your plugin name is as simple as possible, because, the main advantage of using the plugin is to get work done fast, so don’t let your plugin users think for hours to get the function name right.

Ok, having said that, you can create your plugin function within an extended JQ function like this, well I am going to call it a circle itself! so our first plugin function is a circle, so you can call your plugin as $('#divname').circle();

That’s it!.. pretty cool ha?

Now, for the creation of a function

inside the extended function write something like this

$.fn.circle = function() {        
  this.animate({width : 100, height: 100} ,1000);
  this.addClass("_custom_circle");
}

Remember, “this” is already an object, so, it’s not necessary for you to call $(this) within the function.

ok, here is what we are doing.. we are increasing the width and height of the circle along with different CSS appended to it, also, with an animation delay of 1000sec.

Alright,  here is the overall jQuery plugin code:

$(document).ready(function(){
  //initialize the Jquery plugin
  $("#circular").circle();                          
});
                          
(function($){
  $.fn.circle = function() {
    this.animate({width : 100, height: 100} ,1000);
    this.addClass("_custom_circle");
  };        
})(jQuery);

save this script as circle.jquery.js and include it in your index page.

That’s it!!! comments are welcome!! 🙂

You may also read jQuery to export HTML table data into Excel sheet

Shares

Recommended Articles

Leave a Reply

Pin It on Pinterest

Shares