LearnFast.Ninja

Write jQuery plugin tutorial - write your own jQuery plugin

First make sure you import jQuery library. Pass jQuery to a self executing function (closure) that maps it to the dollar sign. Adding a new function property to the jQuery.fn object. Create JSON object for the default settings. Use return so you can use more jQuery inline after your plugin. If new settings exist, merge and override the input with the default settings. Now you can write the core code of your plugin. Now be sure you call your plugin in another script, use ready function for this. Open your browser and see the result of your code.

Working Example:

<html>

<head>

    <title>jQuery plugin</title>

    <!-- Import jQuery library -->

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>

    <!-- jQuery plugin - START -->

    <script type="text/javascript">

        // Pass jQuery to a self executing function (closure) that maps it to the dollar sign.

        (function ($) {

            // Adding a new function property to the jQuery.fn object

            $.fn.myPlugin = function (newSettings) {

                // JSON object - this the default settings ------------------------

                var settings = {

                    'width': '200px',

                    'height': '200px',

                    'backgroundColor': '#f0f0f0'

                };

                return this.each(function () {

                    // If newSettings exist, merge and override the input with the default settings

                    if (newSettings) {

                        $.extend(settings, newSettings);

                    }

                    // Your plugin code here --------------------------------------

                    $(this).css('width', settings.width);

                    $(this).css('height', settings.height);

                    $(this).css('background-color', settings.backgroundColor);

                });

            };

        })(jQuery);

    </script>

    <!-- jQuery plugin - END -->

    <!-- Use the plugin -->

    <script type="text/javascript">

        $().ready(function myfunction() {

            // simple use of the plugin

            $("#Div1").myPlugin();

            // use of the plugin with new settings

            $("#Div2").myPlugin({ 'width': '150px', 'height': '150px', 'backgroundColor': 'Aqua' });

        });

    </script>

</head>

<body>

    <div id="Div1">

        This is regular div with only id.

        <br />

        <br />

        All the cool suff came from the plugin!

    </div>

    <br />

    <br />

    <div id="Div2">

        This is regular div with only id.

        <br />

        <br />

        All the cool suff came from the plugin!

    </div>

</body>

</html>


Result:


Tags

jquery

plugin div