How To Develop a jQuery Plugin

Share this article

How To Develop a jQuery Plugin
jQuery is the most popular JavaScript library and many sites adopt it for dynamic effects and Ajax functionality. However, relatively few developers delve into the depths of plugin development. In this tutorial, we will create simple plugin to explain the basics. Our code will reverse the text within one or more selected nodes — view a demonstration page.

Why Create a jQuery Plugin?

In a word: re-use. By extending jQuery, you create reusable components that can be used on any web page. Your code is encapsulated and there is less risk that you will use the same function names elsewhere.

How jQuery Works

At its core, jQuery is passed DOM elements or a string containing a CSS selector. It returns a jQuery object, which is an array-like collection of DOM nodes. One or more methods can then be chained to this set of nodes, e.g.

// color all <p> tags red
$("p").css("color", "red");
Note: although the jQuery library is named ‘jQuery’, ‘$’ is a shortcut variable that references it. Be aware that other libraries can grab ‘$’ for themselves.

How jQuery Plugins Work

jQuery allows methods to be added to its library. When called, these methods are passed the jQuery object within the JavaScript ‘this’ object. The DOM nodes can be manipulated as required and the method should return ‘this’ so other functions can be chained. Our example plugin will be called using code such as:

// reverse the text in all <p> tags
$("p").reverseText();
We will also add two optional parameters, minlength and maxlength. When defined, the string length must fall between these limits for the reversal to occur.

The Plugin Declaration

Plugins are defined using the jQuery fn function, e.g.

jQuery.fn.reverseText = function(params) { ... };
Using ‘jQuery’ rather than ‘$’ ensures there are no conflicts with other JavaScript libraries. All our internal code should also refer to ‘jQuery’ rather than ‘$’. However, we can save a little typing and reduce the file size using an anonymous function:

(function($) {
	$.fn.reverseText = function(params) { ... };
})(jQuery);
This function runs immediately and is passed jQuery as a parameter named ‘$’. Since ‘$’ is a local variable, we can assume that it always refers to the jQuery library rather than another library that grabbed the global ‘$’ variable first.

Plugin Parameters

We require two parameters for our plugin: minlength and maxlength. It is easiest to define these as function arguments, e.g.

(function($) {
	$.fn.reverseText = function(minlength, maxlength) { ... };
})(jQuery);

// example
$("p").reverseText(0, 100);
But what if we decide to add further parameters later? Our plugin could have dozens of options — parameter handling would quickly become convoluted. As an alternative, we could pass a single JSON object, e.g.

(function($) {
	$.fn.reverseText = function(params) { ... }
})(jQuery);

// example
$("p").reverseText( { minlength: 0, maxlength: 100 } );
The first line in our reverseText function should define a set of default parameters then overwrite these with any user-defined values. The jQuery extend function can handle this for us:

// merge default and user parameters
params = $.extend( {minlength: 0, maxlength: 99999}, params);
Therefore, params.minlength is 0 and params.maxlength is 99999 unless the calling code overrides those values.

The Plugin Code

We can now write our main plugin code:

// traverse all nodes
this.each(function() {

	// express a single node as a jQuery object
	var $t = $(this);

	// find text
	var origText = $t.text(), newText = '';

	// text length within defined limits?
	if (origText.length >= params.minlength &&  origText.length <= params.maxlength) {

		// reverse text
		for (var i = origText.length-1; i >= 0; i--) newText += origText.substr(i, 1);
		$t.text(newText);

	}

});
Explanation:
  1. The this.each function traverses all the jQuery DOM nodes and calls an anonymous function.
  2. Within the function, ‘this’ contains a single node. A jQuery node collection is assigned to $t so we can run jQuery methods.
  3. The variable origText is assigned the text string within the DOM node. newText is set to an empty string.
  4. If the length of origText falls between params.minlength and params.maxlength, the loop creates a reversed text string in newText. The DOM node is then updated accordingly.

Don’t Break the Chain!

Finally, we should remember to return the jQuery object so other methods can be chained:

return this;

The Completed Code

Our plugin code is now complete:

(function($) {

	// jQuery plugin definition
	$.fn.reverseText = function(params) {

		// merge default and user parameters
		params = $.extend( {minlength: 0, maxlength: 99999}, params);

		// traverse all nodes
		this.each(function() {

			// express a single node as a jQuery object
			var $t = $(this);

			// find text
			var origText = $t.text(), newText = '';

			// text length within defined limits?
			if (origText.length >= params.minlength &&  origText.length <= params.maxlength) {

				// reverse text
				for (var i = origText.length-1; i >= 0; i--) newText += origText.substr(i, 1);
				$t.text(newText);

			}

		});

		// allow jQuery chaining
		return this;
	};

})(jQuery);
This file is saved as jquery.reversetext.js. We can then include it in any HTML page after the jQuery library has loaded, e.g.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>jQuery plugin: reverseText demonstration</title>
</head>
<body>

<h1>jQuery plugin: reverseText</h1>
<p>This jQuery plugin reverses all the text in the selected nodes.</p>

<ul>
<li>This text will be reversed</li>
<li>This text will not be reversed</li>
<li>reversed</li>
<li>not reversed</li>
</ul>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.reversetext.js"></script>
<script type="text/javascript">
// reverse even-numbered LI tag text
$("ul li:even").reverseText();
</script>

</body>
</html>
The list in this page now has the text reversed on the first and third bullets (remember, the first item is numbered from 0): reversed text Resources: You should now have a good understanding of jQuery plugin development. The SitePoint JavaScript forum is also a great resource for help and advice. Coming soon: a new three-part tutorial describing how to build a useful page component as a jQuery plugin.

Frequently Asked Questions (FAQs) about Developing a jQuery Plugin

What are the basic steps to create a jQuery plugin?

Creating a jQuery plugin involves a few basic steps. First, you need to define a JavaScript function that will serve as your plugin. This function should be added to jQuery’s prototype to make it available to all jQuery objects. Inside this function, you can use ‘this’ to refer to the current jQuery object. After defining your function, you can use it as a jQuery method. For example, if you named your function ‘myPlugin’, you can use it like this: $(‘#myElement’).myPlugin();

How can I add options to my jQuery plugin?

To add options to your jQuery plugin, you can use the jQuery.extend() method. This method merges the contents of two or more objects into the first object. In the context of a jQuery plugin, you can use it to merge default settings with user-provided options.

How can I make my jQuery plugin chainable?

To make your jQuery plugin chainable, you need to return the jQuery object from your plugin function. This allows the user to chain further jQuery methods after using your plugin. For example, after using your plugin to change the color of an element, the user might want to add a class to it. By returning the jQuery object from your plugin function, you allow this kind of chaining.

How can I add public methods to my jQuery plugin?

To add public methods to your jQuery plugin, you can define them inside your plugin function and attach them to the jQuery object. This allows the user to call these methods on the jQuery object after using your plugin.

How can I add private methods to my jQuery plugin?

Private methods in a jQuery plugin are functions that are only accessible within the plugin itself. You can define these functions inside your plugin function but not attach them to the jQuery object. This keeps them hidden from the user, allowing you to use them for internal calculations or operations.

How can I handle events in my jQuery plugin?

Handling events in a jQuery plugin is similar to handling events in regular jQuery code. You can use jQuery’s event methods, such as .click() or .on(), inside your plugin function. The ‘this’ keyword will refer to the current jQuery object, allowing you to attach event handlers to the elements that are using your plugin.

How can I add custom events to my jQuery plugin?

To add custom events to your jQuery plugin, you can use the .trigger() method. This method allows you to trigger a custom event, which can then be handled using the .on() method. You can pass data to the event handler function by providing it as a second argument to the .trigger() method.

How can I make my jQuery plugin compatible with other plugins?

To make your jQuery plugin compatible with other plugins, you should use the jQuery.noConflict() method. This method allows you to use jQuery’s $ alias without conflicting with other JavaScript libraries that might be using the same alias.

How can I optimize the performance of my jQuery plugin?

There are several ways to optimize the performance of your jQuery plugin. One way is to cache jQuery objects that you use frequently. Another way is to use event delegation to handle events on multiple elements. You can also optimize your selectors to make them faster.

How can I debug my jQuery plugin?

Debugging a jQuery plugin is similar to debugging regular jQuery code. You can use console.log() to print out values and check if they are what you expect. You can also use the debugger statement to pause execution and inspect the current state of your code. If you’re using a browser’s developer tools, you can use breakpoints to pause execution at specific lines of code.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week