Now that we’ve looked at using jQuery plugins, it is absolutely worth understanding how to build them as well. We already briefly touched on the fact that you can extend the native jQuery object if you want to. Just like:
$.myFunction = function() {
console.log("I am a function on the jQuery object.");
};
// call it
$.myFunction();
But that isn’t particularly useful by itself. In order to create a new method for jQuery that you can call on a set of elements, you’ll need to do it like this:
$.fn.myMethod = function() {
// I'm a new method
});
This is exactly the same thing as using .prototype on jQuery, and for the curious, you can read more about that here. Doing it that way means we’ll be able to use that new method on a set of elements. Like:
$("li").myMethod();
You can do whatever you want in side that method, but to be kind of a good jQuery plugin building citizen you should return the same set of elements back out of the plugin.
$.fn.myMethod = function() {
// Do some stuff
return this;
});
That way it will work with chaining. If you don’t do that, and someone tried something like:
$(“li”).myMethod().show();
That would fail, because .show()
would be being called on essentially nothing. Often jQuery plugins are fashioned to loop over each element so that you have direct access to each individual element in the set to do as you need to.
Another good-citizen thing to do is wrap a plugin in an Immediately Invoked Function Expression and pass in jQuery as a parameter to it. That way you can use the $ inside your plugin code more safely. That is because in some situations the $ shorthand for jQuery is unavailable (e.g. a user has used jQuery in “compatibility mode”).
With both of those last two things in place, a plugin structure becomes:
(function($) {
$.fn.myMethod = function() {
return this.each(function() {
// do things
});
};
})(jQuery)
In the screencast we ended up building a simple plugin to add an arrow to the end of any element.
See the Pen rwasH by Chris Coyier (@chriscoyier) on CodePen
Of course, it can get more complex as your ambition to do more goes up.