Create your own custom jQuery plugins

own-jquery-plugin

This tutorial will help you to create your own jQuery plugins from scratch. Here we will demonstrate a simple example to change the font color for a div element.

First let us create the div element


<div id="content">
    <a>sample content</a>
</div>

Now we will define the plugin code.
Suppose if the name of your plugin is ‘myPlugin’ then you need to include your plugin codes inside the below code


(function($){
    $.fn.extend({
        myPlugin: function() {
           //plugin function
        }
    });
})(jQuery);

and then you write the code to change the color for the #content


$(this).css({"color":"red"});

In order to trigger the plugin


jQuery(window).load(function() {
    $('#content').myPlugin();
});

this changes the font color for elements inside #content to red. similarly you can trigger the plugin for other elements

if you want to specify a color which has to be passed as a parameter during plugin execution, then


(function($){
    $.fn.extend({
        myPlugin: function(options) {
            var defaults = {
                color: "grey"
            };
            options = $.extend(defaults, options);

            $(this).css({"color":options.color});
        }
    });
})(jQuery);

here the ‘defaults’ object holds the variables to which you can pass the values

the passed values overwrites the ‘defaults’ values and if no parameters are passed then the default values stay

and pass the parameters while you execute the plugin,


jQuery(window).load(function() {
    $('#content').myPlugin({"color":"red"});
});

If you want to pass more variables, then


var defaults = {
    color:"grey",
    color1:"black",
    color2:"blue"
};

and access them as options.color, options.color1 and options.color2 inside the plugin’s function definition

and when you trigger them, pass the values as follows,


jQuery(window).load(function() {
    $('#content').myPlugin({
        "color":"red",
        "color1":"orange"
    });
});

In the above case where you have not specified the color2 value, the plugin value will take the color blue which is the one defined as default in the plugin definition

Try the above with your custom codes and enjoy creating your own plugins.

Leave a Reply

Your email address will not be published.