7 min read

 

jQuery Plugin Development Beginner’s Guide

jQuery Plugin Development Beginner's Guide

A practical straightforward guide for creating your first jQuery plugin

  • Utilize jQuery’s plugin framework to create a wide range of useful jQuery plugins from scratch
  • Understand development patterns and best practices and move up the ladder to master plugin development
  • Discover the ins and outs of some of the most popular jQuery plugins in action
  • A Beginner’s Guide packed with examples and step-by-step instructions to quickly get your hands dirty in developing high quality jQuery plugins
        Read more about this book      

(For more resources on jQuery, see here.)

Defining our own default plugin structure

To make things easier to remember and apply, we are going to start off with the definition of what we will be referring to when speaking of the basic template that all the plugins we are going to develop should conform to.

Actually, we have already had a quick look at it earlier in the previous chapter, but there’s something more definitely worth saying.

From now on, we will call the following code the default structure for our plugins. This is what we will promptly copy and paste into each file we’re going to write a plugin into.

jQuery.fn.PLUGINNAME = function() {
return this.each(function() {
// code
});
}

Needless to say, the this.each loop iterates all of the matching elements. We return the jQuery object (this) to allow chaining. We extend the jQuery.fn object; all of the code will be put inside the function.

Also:

  • The file name of every plugin we’re going to develop will be
    jquery.PLUGINNAME.js.

    For the moment, remember to always avoid referring to the jQuery object with the dollar sign ($), to prevent possible conflicts with other libraries. We’ll get to using aliases very soon.

  • All of the functions that we write to make our plugin work should be private and not accessible from outside, in an attempt to avoid cluttering and possible backwards incompatibility.
  • If not from the very start, at least at the end, a user will be able to specify options to control the plugin behavior.
  • Default options for the plugin will be publicly accessible to allow for easier customization with minimal code.

The directory that the plugin resides in will also contain two other files, by default:

  • index.html: This is our test page.
  • jquery.js: This is the jQuery library that we need to make things work.

Setting the basics for our first plugin

As our first plugin, we might want to create something uncomplicated but somewhat impressive: what about something that, when the cursor is hovering over an element, substitutes the text contained with some words of our choice?

Time for action – our first plugin, Part I

Getting started in creating jQuery plugins in not difficult at all. For example, creating this simple plugin should help us in understanding how things actually work.

  1. Given that our plugin name is txtHover, create all the directories and files we need by default, and copy over the jquery.js file.

    Creating Our First jQuery Plugin

  2. Copy the default structure for our plugins to the plugin file and make sure the function is named accordingly. It should look like this:

    jQuery.fn.txtHover = function() {
    return this.each(function() {
    // code
    });
    };

  3. Nothing’s easier to do than change the text contained in some element. Inside the plugin function, write the following to let the trick happen:

    jQuery(this).text("Text changed");

  4. To test this in action, we can modify the HTML document to look like this:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="jquery.js"></script>
    <script src="jquery.txthover.js"></script>
    <script>
    $(document).ready(function() {
    $("p#one").txtHover();
    });
    </script>
    </head>
    <body>
    <p id="one">Some text.</p>
    </body>
    </html>

  5. Unfortunately, the result is neither fancy nor satisfactory—something we’ve experienced earlier too. But we’re just getting started; we won’t stop here this time!

    Creating Our First jQuery Plugin

What just happened?

The plugin is working correctly so far. When the page loads, the text is changed to what we had defined into the plugin code.

However, there are a couple of things to pay attention to:

  • The function text() from the jQuery API expects either one or no arguments to be passed: if there is no argument the function returns the current content of the selected element. The text string passed as an argument substitutes the element text otherwise.

    There are, however, some similarities with the html() function, which treats the text it operates on as if it were HTML code. That is, passing any tag to the html() function results in having the element possibly containing other elements after the operation (also, the same applies for getting HTML code from within the element), whereas the this function will just treat the HTML code as plain text and not affect any element hierarchy.

  • The fact that the text cannot be changed, unless we directly modify the code of the plugin.

Getting a step farther

Despite the good realization, our plugin still misses the point. Our goal was to activate the text substitution whenever the mouse pointer hovered over the text to be replaced, whereas our current implementation does it right after the page is loaded.

We put it inside the “document ready” statement, after all!

Time for action – our first plugin, Part II: Hovering

By adding little pieces of code one at a time, we can easily understand what we are going to do and which is the best layout for our plugin. Activating the plugin whenever the mouse pointer hovers over the selected elements is surely another little step that adds up to reach our final goal.

  1. Back to our plugin file, we have to change the code so that the whole mechanism activates when the hover event is triggered. jQuery provides a function called hover(), which we can use to achieve our objective:

    jQuery.fn.txtHover = function() {
    return this.each(function() {
    jQuery(this).hover(function() {
    jQuery(this).text("Mouse hovered");
    });
    });
    };

  2. Now, on to testing. Once the mouse pointer hovers over the text, it is effectively replaced by our string. But even if the mouse is moved, the text doesn’t revert to the original.

    Creating Our First jQuery Plugin

  3. In fact, looking at the hover documentation, we see the function can also take a second argument, that is, the pointer to a function to be executed when the mouse goes off the element.

    Our modified code will now look like the following:

    jQuery.fn.txtHover = function() {
    return this.each(function() {
    var oldTxt = jQuery(this).text();

    jQuery(this).hover(function() {
    jQuery(this).text("Mouse hover");
    }, function() {
    jQuery(this).text(oldTxt);
    });
    });
    };

  4. The result is somewhat better now: the text is changed when we leave the pointer on the paragraph, and is changed again to its original form once the pointer is moved away.

What just happened?

We might be a little more satisfied with this evolution of our plugin, even though it’s far from complete.

Its functioning is fairly straightforward: we have made use of a variable (oldTxt) to store the old content, and we then have proceeded to using two anonymous functions (function(){ }), passed as arguments to the hover() function, to handle the mouse hover event (write our string) and the mouse out event (text back to original).

There’s still something to do though:

  • We have used far too many instances of $(this) in our code and, on a larger scale application, a lot of memory would be wasted this way. It will be incredibly better for performance to make up a variable and use it every time we refer to the element with $(this).
  • The text cannot be changed, unless we directly modify the code of the plugin.

Have a go hero – html () versus text ()

Read the documentation for the html() function.

Create a plugin that, once the mouse pointer hovers over an element, displays the HTML code of its content. The content should then change back to normal once the mouse pointer is moved away from that space.

What happens if the html() and text() functions are used one inside the other, that is, $(sel).text($(sel).html()) or $(sel).html($(sel).text())? Just play around a little bit.

LEAVE A REPLY

Please enter your comment!
Please enter your name here