Sunday, October 7, 2012

How to create a jquery plugin control

This post will explain you to create a jQuery plugin, here we will create a simple plugin which will show your input as an alert. It's just few line of code and very easy to use.

We will start with JS file.


Step 1. Create a JS file. And name it "alertService.js"

To start with JS. First you need to add function as given below to start with your plugin. Rest of your plugin code will come under this.
(function ($) {

})(jQuery);
-----------------------------------------------------------------------------------------------------------------------------
(function ($) {
    //Here we put the name of the plugin..
    // and input parameters will comes in options object.
    $.fn.alertService = function (options) {
        // here we put the default values to the parameters
        var defaults = {
            messege: ""
        };
        // if user pass the parameters then it will pick those. Other wise pick default parameter and put it in options
        var options = $.extend(defaults, options);
        // function which will be called form this plugin.
        function alertMessege() {
            alert("This messege is coming from alertService. And your input text is " + options.messege);
        }
        // Here we call the alertMessege function
        $.fn.alertService = alertMessege();
    };

})(jQuery);
----------------------------------------------------------------------------------------------------------------------------------
Step 2. Now we need to call this plugin form our page.

Here you need to add a Jquery file in your page
I am using jquery-1.4.1.js. You can use any of the version which is available with you.
Add your Plugin js "alertService.js" in your page.

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/js/alertService.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $("body").alertService({
                messege: "Test Pass"
            });
        });
    </script>






No comments:

Post a Comment