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.

______________________

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix