Monday, January 13, 2014

How to create a simple jQuery plugin in less than 10 minutes

Initially i was very much tensed with a thought of creating a jQuery plugin. Only I was aware of the facts, jQuery plugins is nothing but

1) a piece of functionality available throughout your code.
2) a single method you can call on a jQuery selection that performs a series of operations on the selection.

So that's it and i started doing the same. And that too less than 10 minute. Of-course some basic understanding of jQuery and JavaScript needed here. Lets start then :)

Here our aim is to create a plugin which reads data from JSON file and show the records inside the JSON file into a table format.

1) First will create a JSON File, which looks like

/********************JSON Input*********************************/
[
    {
        "studentName": "Shrikant",
        "studentAge": "26",
        "address": "Pune"
    },
    {
        "studentName": "Mayur Tendulkar",
        "studentAge": "28",
        "address": "Pune"
    },
    {
        "studentName": "Dev",
        "studentAge": "20",
        "address": "Pune"
    }
]

/*****************Save the file with .json extension in project directory*******************/

2) Create the HTML Page where the plugin can be implemented

<head runat="server">
    <title>My First jquery plugin </title>
    <script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="js/ZSPlugin.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {

           var ctrl = $('#testPlugin');

<!--Here we have invoked the plugin by the method display, which is the entry point -->
            $('#testPlugin').display('/MyPage.json', ctrl);

        });
    </script>
</head>
<body>
    <div style="width: 60%; margin-right: 20%; margin-left: 20%; text-align: center;">
        <div id="testPlugin">
        </div>
   </div>
</body>



3) Now here is the masterpiece you were waiting for, the plugin code

Create a .js file which contains your plugin code. It can be accessed by placing it in same project directory.




First let see the standard format of a plugin code



(function ($) {
    $.fn.pluignEntryFunction = function (action) {
            };
}
(jQuery));




An example how the code looks

/***********Code Starts***************/
(function ($) {
    $.fn.display = function (input, control) {
            $.getJSON(input, function (data) {
        

    <!----Your code inside--->

    var table = '<table border=1 width=100% >';
            table += '<tr><td colspan=3 align=center>MyJquery Table</td></tr>';
            table += '<tr style=background:Brown;color:yellow;><td align=left>Name</td><td align=left>Age</td><td align=left>Address</td></tr>'
            $.each(data, function (index, item) {
                table += '<tr><td align=left>' + item.studentName + '</td><td align=left>' + item.studentAge + '</td><td align=left>' + item.address + '</td></tr>';
            });
            table += '</table>';

            control.html(table);
        });

    };
}
(jQuery));


/************Code Ends************************/




The $ variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have to make jQuery not use the $ with jQuery.noConflict(). However, this will break our plugin since it is written with the assumption that$ is an alias to the jQuery function. Pass the function jQuery, and name the parameter $
Also it's good practice when writing plugins to only take up one slot within $.fn. This reduces both the chance that your plugin will be overridden, and the chance that your plugin will override other plugins

WoW!! We are done.

Please try this out and let me know if I can help you.

Thank You!!