How to create a simple jquery plugin

jQuery plugin performs set of operations by a single method.The following way to invoke jQuery object methods.


jQuery("selector").method_name(arguments);
//css jquery method example below.

jQuery("a").css("color","red");

Simple Plugin

Here we are creating plugin to make the background blue for a div.For this we need to register a function to $.fn and it will be available just like any other jQuery object method.
To register the function do the following as below. In our case function name is custom which will make the background of the element blue.

$.fn.custom = function() {
    this.css( "background", "blue" );
};
//To call this method on html elements 
jQuery("#main").custom();

Complete example of this plugin

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$.fn.custom = function() {
    this.css( "background", "blue" );
};
jQuery(document).ready(function(){
jQuery("#main").custom();
});
</script>
<div id="main">
Creating simple jquery plugin.
</div>

Leave a Reply