how to create a jquery plugin

Tags: CSS , jQuery

As promised , here is how you create a plugin in jQuery. No sweat and blood, relax and follow.. 🙂

Let us create a simple “jquery circle plugin”.

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

<div id="circular" class="_default_circle">&nbsp;plugin</div>

The important one’s,  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 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 plugin using the jQuery built-in structure

(function($){....... })(jQuery);Next, make sure that your plugin name is as simple as possible, because , the main advantage of using 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 extended JQ function like this, well i am going to call it as circle itself!, so our first plugin function is circle , so you can call your plugin as $('#divname').circle();

That’s it!.. pretty cool ha?

Now, for the creation of 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 , its 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 in your index page.

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

how it looks:

 

Please subscribe for more cool codes 🙂

Code Snippets Plugins

Join Discussion

Your email address will not be published. Required fields are marked *

All code will be displayed literally.