Tuesday, July 5, 2011

Extending jQuery functions, creating plugins

The jQuery wrapper function provides a large number of useful methods we’ll use
again and again in these pages. But no library can anticipate everyone’s needs. It
could be argued that no library should even try to anticipate every possible need;
doing so could result in a large, clunky mass of code that contains little-used features
that merely serve to gum up the works!

We could write our own functions to fill in any gaps, but once we’ve been spoiled
by the jQuery way of doing things, we’ll find that doing things the old-fashioned way is
beyond tedious. By extending jQuery, we can use the powerful features it provides,
particularly in the area of element selection.

Moreover, enterprising jQuery users have extended jQuery with sets of useful functions
that are known as plugins.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="scripts/jquery-1.6.1.min.js" type="text/javascript" >
    </script>
    <script src="scripts/jquery.validate.js" type = "text/javascript">
    </
script>
    <script src ="scripts/jquery.validate-vsdoc.js" type ="text/javascript">
    </
script>
    <script type = "text/javascript">
       <!— Extends jQuery with function named makeRed -->
        $.fn.makeRed = function () {
            return this.each(function () {
                $(this).css({ backgroundColor: 'red' });
            });
        };

        $(function () {
            $("<p>Insert Me Somewhere</p>").insertAfter("#followme");

            $(function () {
                $("#ram").makeRed();
            });
        });
    </script>
</head>
<body>
<p id="followme">follow me!</p>
<div id="ram">Make me Red</div>
</body>
</html>

No comments :

Post a Comment