Create Your First jQuery Plugin

Today is a big day. Up until now we have been using other people’s plugins to improve our web applications. Today we will create our own. It will be an incredibly simple plugin, but will build a foundation for creating more advanced plugins.

This plugin will require you to look at the following pages:

The addresshide.js file contains the actual code for the jQuery Plugin. The php file is our implementation test. What our plugin will do is hide an email address from spam crawlers. It does this by taking in a series of arguments and simply concatenating them together to create a single string. You could do this with simple jQuery or JavaScript code but why not create a plugin? It is a useful function that you will could use over and over again in many different projects.

So on to the explanation of the code.

In the plugin you will notice that there really is not much code here. The most important part of this file is the jQuery.extend({}) line. What this does is tells jQuery that this code is an extension. You will notice that we are using jQuery instead of $. This is because there are other JavaScript libraries use the $ function and this will force the JavaScript to use the jQuery object.

Inside of the extend function you will notice addresshide: function(options) {}. This is the name of our function that is going to be called. This function will be called in the format $.addresshide(opts).

The options parameter is actually a JavaScript object. It contains the following values:

name – The username of the email address (The “josh” in
separator – The separator of the email address (The “@” in
domain – The separator of the email address (The “notarealaddress” in
tld – The separator of the email address (The “com” in
write – This is a boolean value that when true, writes the created email address out using document.write command
selector – This is a string value that places the created email address in selector provided.

Now you can take a look at the PHP file and see how the plugin is utilized. You simply call it using the code described above, giving it the options required and you have yourself your first plugin.

What I would recommend is creating your own “jQuery” library that is your own personal toolbox of things that make your life easier.