Chapter 9. Extending jQuery with Plugins

jQuery is written so that it is easy to add new functionality. Modules that add new functionality are called plugins, and you can find many of them at http://plugins.jquery.com. jQuery plugins are just ordinary files of JavaScript code, and to use them in your web pages, you just include them with a <script> tag as you would any other JavaScript library (you must include plugins after you include jQuery itself, of course).

It is almost trivially easy to write your own jQuery extensions. The trick is to know that jQuery.fn is the prototype object for all jQuery objects. If you add a function to this object, that function becomes a jQuery method. Here is an example:

jQuery.fn.println = function() {
    // Join arguments into a space-separated string
    var msg = Array.prototype.join.call(arguments, " ");
    // Loop through each element in the jQuery object
    this.each(function() {
        // For each one, append the string as plain text,
        jQuery(this).append(document.createTextNode(msg))
            .append("<br/>");  // then append a <br/>.
    });
    // Return the jQuery object for method chaining
    return this;
};

With that jQuery.fn.println function defined, we can now invoke a println() method on any jQuery object:

$("#debug").println("x = ", x, "; y = ", y);

It is common practice to add new methods to jQuery.fn. If you use the each() method to “manually” iterate through the elements in a jQuery object and perform some kind of operation on them, consider whether it might make sense ...

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.