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 past two months, this column has looked at the jQuery library for JavaScript programming. jQuery is one of several popular libraries (like Prototype, YUI and Dojo) that have sprouted up in the last few years, making it possible to use JavaScript in ways that make the Web more satisfying and responsive by incorporating desktop-like behavior.

Part of the reason for jQuery's popularity is the huge library of plugins available for it. There are plugins for almost any type of functionality you can imagine—from GUI widgets to navigational aids to textual transformations. Plugins make it possible to isolate and reuse certain behaviors, achieving a goal known in the Ruby world as DRY (don't repeat yourself).

As I showed last month, using a plugin is generally quite easy. Download the plugin; install any CSS and JavaScript files that come with it, and then incorporate the JavaScript file into one or more HTML pages on your site, using a standard <script> tag. Finally, attach the plugin to one or more elements on the page, using jQuery's event-handling functions, typically inserted into $(document).ready.

If you use jQuery, and you find yourself repeating the same JavaScript patterns over and over, you might want to consider writing your own plugin. Whether you distribute that plugin to the rest of the jQuery community depends on a number of factors, but by making it a plugin, you make it possible for all of your applications to load and use the library in a similar way.

Hubellubo Wuborld

A jQuery plugin is a packaging mechanism for your JavaScript code. This means in order to create your plugin, you first must have some JavaScript that needs packaging.

So, as an example this month, I've decided to create a simple translator into Ubbi Dubbi. Ubbi Dubbi, as some of you may know, is a “secret” language for children that was popularized in the United States by the public TV show Zoom in the 1970s (when I watched it), and then again in the 1990s. The rules for Ubbi Dubbi are simple. Every vowel (a, e, i, o and u) is prefixed with the letters ub. So, hello becomes hubellubo. It's not very hard to teach yourself to speak Ubbi Dubbi, and it sounds hilarious. Give it a try!

In any event, let's begin by creating a basic JavaScript program, using jQuery, that turns text into Ubbi Dubbi when the mouse cursor hovers over it. Let's start with a simple HTML file called ubbi.html (Listing 1). As you can see, there is no JavaScript in this file. Rather, we will use the “unobtrusive” style that jQuery encourages, writing our JavaScript in a separate file (ubbi.js, Listing 2), which we then include by means of a <script> tag.

The HTML itself is not very surprising or exciting. We have two paragraphs of text, each of which has the class ubbi assigned to it. In the JavaScript file, we use the .ubbi selector to set handlers for the mouseover and mouseout events. This is where the magic really happens. When the mouse hovers over the specified paragraph, the text is transformed into Ubbi Dubbi. When the mouse moves away, the text returns to its original form.

The translation depends on our ubbify function, which is defined as follows:

function ubbify(text) {
    return text.replace(/([aeiou])/gi, 'ub$1');
}

The above JavaScript function takes a single textual argument. It replaces any vowel with the string ub, followed by the letter that was replaced. Admittedly, there's a bug here related to capitalized words that begin with a vowel. Fixing that is left as an exercise for the reader.

Our mouseover handler is defined as follows:

$(".ubbi").bind('mouseover',
                function() {
                    var original_text = $(this).html();
                    $(this).attr({originalText: original_text});
                    $(this).html(ubbify(original_text));
                });

This works by using jQuery's bind function, which invokes a function when a particular event fires on an HTML element (or collection of elements). So in this particular case, we tell JavaScript that every HTML element with a class of ubbi should invoke our function when the mouse cursor hovers over it. The function itself grabs the original text, puts it into an attribute named originalText, and then replaces the original text with the ubbified text.

The mouseout handler is similar, doing roughly the reverse, but without the ubbification:

$(".ubbi").bind('mouseout',
                function() {
                    $(this).html($(this).attr("originalText"));
                    $(this).attr({originalText: ""});
                });

To add a bit of pizzazz and styling, we also have ubbi.css, which uses the .ubbi:hover pseudo-selector to colorize and italicize the text when the mouse is hovering over it (Listing 3).

______________________

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