Writing Your Own jQuery Plugins

jQuery is great. It’s cross-browser, easy to learn, and makes adding interactivity to your website a breeze. It also comes with plenty of plugins to do almost whatever you need it to do.

But what if you can’t find just the right plugin to suit your needs? Or you’re just looking to keep your project DRY by combining some oft-used functionality into one nice, neat package? The solution might be to roll your own plugin to meet exactly your needs.

Writing your own jQuery plugin isn’t as hard as it might seem at first. This tutorial will go through the process of writing a simple plugin, adding some options, and even perform a callback.
Setting Up

We’ll start with the old chesnut of programming tutorials, a “Hello, World!” plugin. Before we can do anything, we need to establish our file and link it to our HTML document. First, we’ll create our plugin file and put it in the “js” directory of our website. It’s traditional to start our filename with “jquery,” followed by the actual plugin name, so we’ll call this “jquery.hello-world.js”.

folder

Next, we’ll need to make sure our plugin file, as well as it’s jQuery core big brother, are linked in our HTML file, so place the following two lines at the bottom of your HTML document, just before the closing body tag:

The jQuery Plugin Structure

jQuery comes with all the necessary hooks to build your plugin file easily. But we still want to be mindful of good JavaScript practices, and make sure we keep everything inside a local scope. We’ll start with the very basic shell of a traditional jQuery plugin:

(function($) {
$.fn.helloWorld = function() {
// Future home of "Hello, World!"
}
}(jQuery));

Let’s take a quick moment to understand what’s going on. By including everything in the (function() {}) self-enclosed JavaScript pattern, we’re making sure that all the variables in our plugin will stay safely outside of the global namespace. We don’t want to cause any collisions with any other JavaScript used on the page, after all.

The other thing you might notice is that we’re defining our plugin as if jQuery was in it’s “no-conflict” mode. Again, we’re seeking to avoid colliding with other JavaScript on the page, and thus we want to make sure that our plugin isn’t reliant on the default $, which could be used by another library.

Finally, $.fn is jQuery’s way of allowing you to define your plugin, which we’ve named helloWorld. With all of our pieces in place, let’s actually do something!
Making Our Plugin Do Something

For our plugin, we’re going to do something pretty silly, but also simple enough for our demonstration purposes, and that is to change all the text for the acted upon elements with (what else?) the text “Hello, World!”.

(function($) {
$.fn.helloWorld = function() {
this.each( function() {
$(this).text("Hello, World!");
});
}
}(jQuery));

When we’re invoking the plugin by attaching it to a jQuery selector, the object we’re acting upon is already a jQuery object, so we don’t need to wrap it in the $(this) structure you’re used to. However, once we start looping through each instance of the matching selector, we use the $(this) structure as we would any time we ran our selectors through $.each().

We would invoke the plugin as you’re already familiar, like so:

$(document).ready( function() {
$('h2').helloWorld();
});

We’re not quite done yet. While our plugin technically works, it’s living in its own little isolated world. That is, if you try and chain another jQuery action onto it, nothing’s going to happen because our plugin has led to a dead end. To fix this, be sure to return the results of the plugin as it loops through the DOM elements:

(function($) {
$.fn.helloWorld = function() {
return this.each( function() {
$(this).text("Hello, World!");
});
}
}(jQuery));

And congratulations! You’ve just written you’re first jQuery plugin!

Well, we could start by just adding an argument. Let’s take our plugin above, and instead of hard-coding the text into the plugin, we can replace it with a variable and pass that along when we invoke the plugin.

(function($) {
$.fn.helloWorld = function( customText ) {
return this.each( function() {
$(this).text( customText );
});
}
}(jQuery));

which we now use as the parameter of our plugin:

$(document).ready( function() {
$('h2').helloWorld('¡Hola, mundo!');
});

$.extend method:

(function($) {
$.fn.helloWorld = function( options ) {

// Establish our default settings
var settings = $.extend({
text : 'Hello, World!',
color : null,
fontStyle : null
}, options);

return this.each( function() {
// We'll get back to this in a moment
});
}
}(jQuery));

Now we have a settings object that, when the plugin is invoked devoid of any parameters, will use what we’ve established as the default text. We also have two other properties of our settings object, “color” and “fontStyle”, that have no default beyond null. For this plugin, we don’t need to establish any color or font style beyond what is laid out in our CSS, but they’re there for the overriding if we want. We just have to make use of them:

return this.each( function() {
$(this).text( settings.text );

if ( settings.color ) {
$(this).css( 'color', settings.color );
}

if ( settings.fontStyle ) {
$(this).css( 'font-style', settings.fontStyle );
}
});

Fortunately, our plugin can now handle color, fontStyle requests:

$('h2').helloWorld({
text : 'Salut, le monde!',
color : '#005dff',
fontStyle : 'italic'
});

Advertisements

One thought on “Writing Your Own jQuery Plugins

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s