This post is Part 3 in The Beginner’s Guide To Writing a jQuery Plugin.
Perhaps the biggest challenge of working in software development is staying up-to-date with all of the resources, languages, and technologies that are available.
In addition to being well-versed in all of the above, we have to be prepared learn new things as they become available.
Developing a plugin for jQuery is no different so before begin writing code, we need to take a look at jQuery’s model for plugin development.
1. Bookmark Documentation
Just as most major products ship with a user manual, most major software applications ship with documentation. Specifically, they detail what’s available in the API.
jQuery is no different. If you’re planning to continue doing work with the library, I recommend bookmarking the jQuery Documentation and spend some time reading through the available functions and examples.
The jQuery Documentaton provides a great article on Plugin Authoring, but we’re attempting to explore this from the beginner’s perspective.
So we’ll do that.
2. Regarding Objects and Functions
Because the library is designed to be extended, jQuery makes it relatively easy to get started crafting your own plugin. Arguably the most basic plugin is a function that’s added to the jQuery object.
Note that an object is a collection of functions. Think of objects as a physical thing that perform actions. Those actions are called by the developer – actions are functions.
For example, a light switch is an object. You can flip a light switch up or down. Programatically, a light switch may look like this:
[cc lang=”javascript”]
lightSwitch.flipUp();
lightSwitch.flipDown();
[/cc]
Make sense?
3. Custom Functions in jQuery
Similarly, jQuery is an object that has a number of functions that allow you to manipulate elements such as divs, images, anchors, paragraphs, etc. on a web page.
To begin adding our own functions, we need to add them to the jQuery fn object. This is done by declaring the name of your function on the jQuery function object and assigning it a function.
To get started, we’d write the following code:
[cc lang=”javascript”]
// add the sayHello function to jQuery’s function object
jQuery.fn.sayHello = function() {
// TODO
};
[/cc]
One of the biggest advantages of using jQuery is the way that you can call function after function after function. For example:
[cc lang=”javascript”]
$(‘.active’).removeClass(‘active’).addClass(‘inactive’);
[/cc]
This is called chaining and it’s what gives jQuery so much flexibility.
It’s a good practice to make sure that your plugin will allow other developers to maintain the ability to call functions after yours.
For example, other developers may want to write:
[cc lang=”javascript”]
jQuery(‘body’).sayHello().css(‘background’, ‘#efefef’);
[/cc]
As such, we want to make sure that we’re properly returning the correct object. In jQuery, the standard way of doing this is:
[cc lang=”javascript”]
// add the sayHello function to jQuery’s function object
jQuery.fn.sayHello = function() {
return this.each(function() {
// TODO
});
});
[/cc]
This will allow future developers to call your method on a any collection of DOM elements and return the jQuery object ultimately allowing them to chain their methods.
Finally, let’s implement a simple method that will display the classical computer science greeting within the elements that are passed into the jQuery function:
[cc lang=”javascript”]
jQuery(‘body’).append(‘
Hello world!
‘);
[/cc]
The final plugin should look like this:
[cc lang=”javascript”]
// add the sayHello function to jQuery’s function object
jQuery.fn.sayHello = function() {
return this.each(function() {
jQuery(‘body’).append(‘
Hello world!
‘);
});
});
[/cc]
4. Testing the Plugin
In order to test out our plugin, we need to setup our HTML Sandbox that we detailed in Part 1.
First, save the plugin code into the JavaScript directory that we created. jQuery plugins follow a specific naming convention. In our case, the file should be named jquery.sayhello.js.
Next, we need to create a file that will execute our plugin. In your text editor, add the following code:
[cc lang=”javascript”]
$(function() {
// call our sayHello function on the body of the page then change the background color
$(‘body’).sayHello().css(‘background’, ‘#efefef’);
});
[/cc]
Save this in the JavaScript directory, as well.
Finally, include the scripts in your HTML page. The final source code should look like this:
[cc lang=”html”]
jQuery Plugin Development Sandbox
[/cc]
Load the page up in your browser and you should see Hello world appear on the page.
Cool, huh? Stuff starting to make sense?
You can download a working copy of this post here. Explore the code and try out a few other things. In the next post, we’ll begin to actually implement our slideshow.
Brian Notess says
Good stuff! As always.
I have to admit the jQuery syntax is still a bit mysterious to me. I’ve read the documentation but still can’t figure out why exactly you need to pass “jQuery” instead of the dollar sign. I know it has to do with conflicting libraries.
Is there a reason you didn’t add your function using “(function( $ ){……})( jQuery );”
Just a little syntax confusion herre 😉
Tom McFarlin says
I’m going to be covering that later in this series.
Generally speaking, it’s so that you can use the $ function within the context of your plugin, but I’ll get more in depth soon :).
James Finley says
The quick answer: conflict prevention. A lot of JavaScript scripts, widgets, etc. use the $. jQuery can be called as jQuery() or $(), and you can so jQuery.noConflict() which removes the $ from the global scope. Plugins should never use the $ because of this. They need to work in all environments.
Tom McFarlin says
Straight up. Good stuff, James!