At the Forge - Writing jQuery Plugins

If you're using jQuery, you already know JavaScript, so now it's time to write your own jQuery plugins.

The combination of the CSS and JavaScript is fun and a bit exciting. Normally, the text looks as you would expect. But, when you move your mouse over a piece of text, it is transformed into Ubbi Dubbi. Prubetty cubo-ubol, rubight?

Making a Plugin

This JavaScript works just fine. However, perhaps there is a general need for Ubbi Dubbi translators that are active when the mouse hovers over text. It would be nice if someone simply could make every paragraph in a document automatically Ubbified with:

$(document).ready(function() {
                      $("p").ubbify();
                  });

In order to do this, let's create a jQuery plugin. The plugin, when incorporated, will add a new function to the jQuery object. This means that instead of our ubbify function being in the global namespace and instead of being invoked from within an event handler, we will define a function in the jQuery namespace, and it will be invoked by handlers that also are defined in that namespace.

To make this happen, we need to restructure things a bit. First, we need to rename our JavaScript file, because every plugin needs to be of the format jquery.PLUGIN.js. In this case, I will call it jquery.ubbi.js.

Next, we need to define our ubbify function such that the global jQuery object will recognize it. To do this, we define ubbify inside the jQuery namespace:

$.fn.ubbify = function () {
                  // implementation goes here
              }

Wait a second—what is this $.fn that we are defining inside of? It turns out that if we want to define a global method for the jQuery object, normally aliased to $, we must assign that function to the $.fn object.

But, wait again—it is possible to redefine $ so that it is no longer an alias to the $ function. That allows jQuery to play nicely with JavaScript libraries such as Prototype, which also uses $, but in a very different way. For this reason, many jQuery plugin tutorials tell you not to use $, but rather the full jQuery object, like so:

jQuery.fn.ubbify = function () {
                       // implementation goes here
                   }

Another solution is to wrap the entire function definition inside a closure (that is, a function with state), giving the closure the jQuery object as an environment with variable bindings:

($.fn.ubbify = function () {
                   // implementation goes here
               });

Now that we have gotten this out of the way, we can define our function inside its new plugin home. Listing 4 contains jquery.ubbi.js, a jQuery plugin that does everything we did before, but within the context of a plugin.

One of the most interesting things about jQuery is the fact that it accepts any number of arguments, thanks to CSS selectors. A function might be called for a single paragraph, identified via a DOM ID. Or, it might be invoked on many tags, or on tags with a certain class. Our function needs to handle any or all of these, and when it's done, our function must then return the jQuery object, so that its use can be “chained” to another set of instructions.

We do this by iterating over each argument and by returning the results, as follows:

return this.each(
    function() {
        ...
    });

jQuery defines .each to be an iterator that operates on each element of the object that invoked it. In this case, we take each of the submitted elements and pass them to a function. The function, of course, assigns the event handlers mouseover and mouseout. Notice how the functions are now invoked on $(this), the jQuery version of the current element.

Finally, our ubbify function is defined privately within the $.fn.ubbi definition. Our ubbify function is available to any and all users within our definition of $.fn.ubbi, which is admittedly a very small number of functions for now.

With our plugin in place, all we have to do is tell our HTML file to load the plugin and to invoke it in the right way:


<script type="text/javascript" src="jquery.ubbi.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
                        $(".ubbi").ubbi();
                    });
</script>

Notice that jquery.js must be loaded before any plugins are loaded. We can apply our ubbi plugin to all of the paragraphs on a page with the following:

$("p").ubbi();

With our Ubbi plugin (plubugubin?) in place, it now has become that much easier to provide people with Ubbi Dubbi translations. Thanks to jQuery's plugin mechanism, we can distribute our plugin for others to use too, without having to read or understand the code. Our modified simple HTML file is shown in Listing 5.

______________________

Webcast
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers

Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.

Learn More

Sponsored by AMD

White Paper
Red Hat White Paper: Using an Open Source Framework to Catch the Bad Guy

Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6

Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.

Learn more about catching the bad guy in this free white paper.

Learn More

Sponsored by DLT Solutions