How to create a simple jQuery plugin with example

jQuery is one of the most popular, if not the most, JavaScript library in use today on the web. It’s been around for a while and web developers have been using it for almost anything from animation to dynamic styling to complex rich user interface applications.

I have to be honest, I like jQuery. I’ve been using other JavaScript libraries like YUI or Dojo, and they all have their advantages and draw backs, but to me jQuery seems to have the most natural usage. Of course, it’s just a matter of taste here.

In this post I will show you one of the features of jQuery: the jQuery plugins. Plugins is a way to extend the functionality of jQuery creating components similar to the core components of jQuery. To explain better what plugins are I will show you how to create a simple jQuery plugin. The plugin I though of creating is called linkHighlighter and what it will do is take all the links on a page and highlighting them by changing the background color.

Basic jQuery plugin structure

The jQuery documentation is very clean and straight forwards, another reason to like jQuery, and regarding plugins the documentation is quite simple to follow and you can find it here How to create a basic plugin.

jQuery is used by calling various functions of the root object called jQuery which is most of the times aliased using $. Creating a plugin means simply adding a function containing your code to the root object. You don’t add your function directly in the root, but in the $.fn object.

$.fn.linkHighlighter = function(){.... my function ....}

After doing this you can simply call the plugin like this

$(HTML elements).linkHighlighter();

and this will call on your implementation and apply it to the selected HTML element(s).

The right way to write jQuery plugins

While the code described above will work for a simple example, you have to keep in mind that in order for the plugin to work properly in all situations there are some steps to take when writing a plugin.

First, you have to make sure that the $ is not already in use for pointing to something else than the jQuery object. Also, sometimes it happens that 2 or more jQuery versions are in use – this is not recommended at all – then conflicts may occur and the code might not be executed correctly.

jQuery offers the possibility of avoiding naming conflicts like this

// restores the $ alias to it's original 
//(in case other libraries make use of it)
$.noConflict();

You can read more about this in the jQuery API reference for noConflict.

Also, a neat trick that you can do is to use anonymous function call in which you can locally use the $ alias.

//anonymous function with $ as parameter
//the function is called using the jQuery object
//allowing you to use $ as an alias for the jQuery object
(function($){
.....
})(jQuery);

Inside the anonymous function you have to add your plugin to the $.fn object like this

$.noConflict();
(function($){
	$.fn.linkHighlighter = function(){
		//code for the plugin goes here
		...
	};
})(jQuery);

There are 2 more things to add to the code for it to become a template for writing jQuery plugins the right way:

  1. options – almost all plugins will have a mechanism through which you can pass parameters and customize the behavior of the plugin;
  2. chaining – in order for the plug in to behave like all other components in jQuery, you need that the function implementing the logic of your plugin to return a reference to itself such that other calls can be made in a “chain”; eg. $(“#id”).linkHighlighter().css({“backgroundColor”:”red”}); this code executes the plugin and then the objects selected have their background color set to red; this is made possible by chaining so theoretically you could continue calling functions on the selected elements an indefinite number of times by using the dot operator.

Let’s see how our plugin will look like with the 2 included

 

$.noConflict();
(function($){
	$.fn.linkHighlighter = function(options){
                //use extend to merge the parameters given by the user of
                //the plugin with the default options
                var settings = $.extend(
                             {
                               "highlightColor":"red",
                               "linkColor":"white"
                             },options);
		//code for the plugin goes here
		...
                //return a reference to the jQuery object for chaining
                return this;
	};
})(jQuery);

So, we’ve used the extend function to merge the parameters given by the user with the plugin default parameters and we have return a reference to the jQuery object which will allow calling other jQuery functions on the objects selected after we call the plugin.

That’s the basic correct structure for a jQuery plugin. Now let’s see the full plugin code, how to call it and what it does.

Link highlighter jQuery plugin source code

For the plugin to actually do something we will have to add the code that actually highlights the links in the document. To do this we will have to use the parameters passed to the plugin and set the CSS styles for the background color of the links and the text color of the link.

So the code will look something like:

$.noConflict();
(function($){
	$.fn.linkHighlighter = function(options){
                //use extend to merge the parameters given by the user of
                //the plugin with the default options
                var settings = $.extend(
                             {
                               "highlightColor":"red",
                               "linkColor":"white"
                             },options);
		//code for the plugin goes here
		this.css(
                         {
                           "backgroundColor":settings.highlightColor,
                           "color":settings.linkColor
                         }
                );
                //return a reference to the jQuery object for chaining
                return this;
	};
})(jQuery);

The css jQuery function will set the style for the elements selected in the plugin. To call the plugin you need to do the following in your script section:

jQuery("a").linkHighlighter();

This will select all links in the document and highlight them using the default colors. To customize the colors you need to call the plugin like this:

jQuery("a").linkHighlighter(
     {"highlightColor":"yellow","linkColor":"black"}
);

To see this plugin in action I’ve added it to the page so if you click on this link you activate the plugin with the default settings and this link with the customized colors. Give it a try!

Hope you’ve enjoyed this article and found it very useful. Don’t hesitate to drop me a comment if you have any comments or remarks.

John Negoita

View posts by John Negoita
I'm a Java programmer, been into programming since 1999 and having tons of fun with it.

1 Comment

  1. […] you want to create your own, you can read my other post on how to create a jQuery plugin, because I will not go into details about that. I will assume that you already have one […]

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top