jQuery Plugins create custom plugin

How to create jQuery Custom Plugins

 

jQuery Home

 

 

What is jQuery plugin ?

 

A jQuery plugin is simply a piece of code written in a standard JavaScript file, that we use to extend jQuery's prototype object. By extending, all jQuery objects to inherit any methods that you add.

 In this blog post we are going to learn how to create our own plugin in using jQuery.

  

How to create a custom Plugin?

 


It is very simple to write your own plug-in in jQuery. 

 

Following is the syntax to create a custom  method:


jQuery.fn.methodName = methodDefinition;


The use of the jQuery prefix, eliminates any possible name collisions with files intended for use with other libraries.


Top

Example:
 

Following is a small plug-in to have setcolor method for styling purpose. 

To create a jQuery plugin, firstly create a file named jquery-myplugin.js in /js folder.

Save the following code in jquery.myplugin .js. Here, myplugin is the name of our plugin.

This is our plugin code.

jQuery.fn. setcolor = function() { 

return this.each(function() 

$(this).css("color", "green");

}); 

}

 

Here is the example showing usage of setcolor() method. Assuming we put jquery.myplugin.js file in /js subdirectory: 

 

Createa a sample index.html files with a 2 elements one is div and pragramph.  same as show below.


index.html

 

 

<html>
<head>
<title>the title</title>
 
<script src="js/jquery-1.3.2.min.js" type="text/javascript" ></script>
<script src="js/jquery.myplugin.js" type="text/javascript"></script>
 
<script>
$(document).ready(function() {
$("div").setcolor();
$("p").setcolor();
});
</script>
 
</head>
 
<body>
<p>This is paragraph</p>
<div>This is division</div>
</body>

</html> 

 

Open the above file  in a browser

This would produce following result:

This is paragraph
This is division 
  
 
 
Example2:

 

A custom method with a parameter

 

Passing parameter to function:

 

Create a file jquery.myplugin2.js with the following code. Save it in /js folder.

 
 
jQuery.fn.setcolor2 = function(c) {
return this.each(function() {
$(this).css("color", c);
});
};
 
 

 

 

This  example showing usage of setcolor2() method.  Link the file in html and apply the method (setcolor2) to HTML elements.


index2.html

 

<html>
<head>
<title>the title</title>
 
<script src="js/jquery-1.3.2.min.js" type="text/javascript" ></script>
<script src="js/jquery.myplugin2.js" type="text/javascript"></script>
 
<script>
$(document).ready(function() {
$("div").setcolor2("red");
$("p").setcolor2("green");
});
</script>
 
</head>
 
<body>
<p>This is paragraph</p>
<div>This is division</div>
</body>
</html>

 

 output:

 

This is paragraph

This is division
 
 
 
 


 
 
 
jQuery Plugins create custom plugin

  

 

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP