Extending jQuery with Plug-ins
jQuery is written so that it is easy to add new functionality.
Modules that add new functionality are called
plug-ins, and you can find many of them at http://plugins.jquery.com. jQuery plug-ins are just
ordinary files of JavaScript code, and to use them in your web pages,
you just include them with a <script>
element as you would any
other JavaScript library (you must include plug-ins 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 all the 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, then append a <br/>.
jQuery
(
this
).
append
(
document
.
createTextNode
(
msg
)).
append
(
"<br/>"
);
});
// Return the unmodified 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 like
this:
$
(
"#debug"
).
println
(
"x = "
,
x
,
"; y = "
,
y
);
It is common practice to add new methods to jQuery.fn
. If you find yourself using the
each()
method to “manually” iterate through the elements in a jQuery object and perform some kind of operation on them, ...
Get JavaScript: The Definitive Guide, 6th Edition 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.