O'Reilly logo

JavaScript Cookbook by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.7. Convert Your Library to a jQuery Plug-in

Problem

You want to convert your library methods and functions into a jQuery plug-in for use by others.

Solution

If you want your method to participate in the jQuery chain and be used with selectors, assign your method to the jQuery.fn property:

jQuery.fn.increaseWidth = function() {
   return this.each(function() {
      var width = $(this).width() + 10;
      $(this).width(width);
   });
};

If your plug-in has one or more separate functions that do not need to participate in the jQuery chain, or be attached to a selector, create a jQuery function directly on the jQuery object:

jQuery.bbHelloWorld = function(who) {
   alert ("Hello " + who + "!");
};

If your function uses the jQuery dollar sign function ($) and you’re concerned that the library could be used with other libraries that make use of $, wrap your function in an anonymous function. Instead of using the following jQuery method approach:

jQuery.fn.flashBlueRed = function() {
    return this.each(function() {
      var hex = rgb2hex($(this).css("background-color"));
      if (hex == "#0000ff") {
        $(this).css("background-color", "#ff0000");
      } else {
        $(this).css("background-color", "#0000ff");
      }
    });
 };

use the following anonymous function syntax:

;(function($) {
   $.fn.flashBlueRed = function() {
      return this.each(function() {
         var hex = rgb2hex($(this).css("background-color"));
         if (hex == "#0000ff") {
            $(this).css("background-color", "#ff0000");
         } else {
            $(this).css("background-color", "#0000ff");
         }
       });
    };
})(jQuery);

Discussion

It’s relatively simple to create a jQuery plug-in once you understand the nuances of the jQuery plug-in infrastructure.

If you’re interested in creating a jQuery method that can be used with a jQuery selector and participate in the jQuery chain, you’ll use the first syntax shown in the solution:

jQuery.fn.increaseWidth = function() {
   return this.each(function() {
      var width = $(this).width() + 10;
      $(this).width(width);
   });
};

However, if you want to make use of the dollar sign function ($) within the code, but still have the plug-in work within a multiple library setting, wrap the method in an anonymous function:

;(function($) {
   $.fn.flashBlueRed = function() {
      return this.each(function() {
         var hex = rgb2hex($(this).css("background-color"));
         if (hex == "#0000ff") {
            $(this).css("background-color", "#ff0000");
         } else {
            $(this).css("background-color", "#0000ff");
         }
       });
    };
})(jQuery);

Notice the following line in both examples:

return this.each(function () {

This code is necessary to allow the method to work on whatever is returned by the selector, regardless of whether it’s a single item or a group of items. The line begins the code block that includes your actual method code.

Check out the semi-colon (;) just before the anonymous function. I picked this trick up from Cody Lindley in jQuery Cookbook (O’Reilly). Putting the semicolon before the anonymous function ensures that the function won’t break if another plug-in forgets to terminate a method or function with a semi-colon.

If you’re only interested in adding a jQuery function that isn’t part of the jQuery chain or which makes use of a selector, use the jQuery function syntax:

jQuery.bbHelloWorld = function(who) {
   alert ("Hello " + who + "!");
};

Once you have created your plug-in code, package it in a separate file; to use the code, all someone has to do is include the script, following the jQuery script.

An example of a plug-in file is shown in Example 17-3. This file has a couple of functions, specific to converting an RGB value to a hexadecimal. All of the functions are added to the jQuery object, and each is preceded by “bb”, to act as namespace for the function.

The bbGetRGB function in the library is actually a function that exists as an internal (not publicly exposed) function within the jQuery User Interface (UI) library. It was originally created by Blair Mitchelmore for the highlightFade jQuery plug-in. However, I didn’t want to include the jQuery UI, so I just borrowed the function for the example.

Example 17-3. A jQuery plug-in

// Parse strings looking for color tuples [255,255,255]
// pulled from internal jQuery function
jQuery.bbGetRGB = function(color) {
    var result;

    // Check if we're already dealing with an array of colors
    if ( color && color.constructor == Array && color.length == 3 )
        return color;

    // Look for rgb(num,num,num)
    if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-
9]{1,3})\s*\)/.exec(color))
         return [parseInt(result[1],10), parseInt(result[2],10),
parseInt(result[3],10)];

    // Look for rgb(num%,num%,num%)
    if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.
[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
         return [parseFloat(result[1])*2.55, parseFloat(result[2])*
2.55, parseFloat(result[3])*2.55];

    // Look for #a0b1c2
    if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.
exec(color))
         return [parseInt(result[1],16), parseInt(result[2],16),
parseInt(result[3],16)];

    // Look for #fff
    if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.
exec(color))
        return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16),
parseInt(result[3]+result[3],16)];

    // Look for rgba(0, 0, 0, 0) == transparent in Safari 3
    if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
        return colors['transparent'];

    // Otherwise, we're most likely dealing with a named color
        return colors[$.trim(color).toLowerCase()];
};

jQuery.bbPadHex = function (value) {
    if (value.toString().length == 1) {
         value = "0" + value;
     }
     return value;
};

jQuery.bbConvertRGBtoHex = function(rgbString) {
     var colors = $.bbGetRGB(rgbString);
     var red = $.bbPadHex(parseInt(colors[0]).toString(16));
     var green = $.bbPadHex(parseInt(colors[1]).toString(16));
     var blue = $.bbPadHex(parseInt(colors[2]).toString(16));

     return "#" + red + green + blue;
};

bbPadHex, bbConvertRGBtoHex, and bbGetRGB are added as jQuery functions, the flashBlueRed method is wrapped in an anonymous function, and the increaseWidth method is a straight jQuery method. Example 17-4 shows the two methods in action. Notice how the increaseWidth method is chained to the flashBlueRed method, and both work on the element returned with the jQuery selector.

Example 17-4. Web page and application that use the new plug-in

<!doctype html>
<html>
  <head>
  <style>
  #test
  {
    background-color: #0000ff;
    width: 500px;
    padding: 10px;
    color: #ffffff;
    font-weight: bold;
    font-size: larger;
  }
  </style>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="basic.js"></script>

    <script type="text/javascript">

       $(document).ready(function() {
         $("#test").click(function() {
             $(this).flashBlueRed().increaseWidth();
         });
       });
    </script>
  </head>
  <body>
  <div id="test">
    hi, click me to change color
  </div>
  </body>
</html>

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required