Create a jQuery Plugin

Writing a jQuery plugin is helpful when you want to reuse or apply repeatedly some functionality to selected elements in a page.

A jQuery plugin is a new method which is available to the jQuery() or $() function along with the other standard library methods.

A Simple jQuery Plugin

We start by creating a simple jQuery plugin to underline texts which are inside elements retrieved by some selector.

A jQuery plugin is defined by some name that you conjure, which is added after the $.fn object, which is actually an alias for $.prototype or jQuery.prototype (check it here). The $.fn object encompasses all jQuery object methods, and hence the custom method we are about to define would also need to be part of it as well. To see what I mean, press F12 to open your browser's console and type

					
						$.fn.
					
				

or

					
						jQuery.prototype.
					
				

You can see that all the object methods it contains pops up in the suggested list, all the way down beneath the scrollbar.

jquery prototype

What we are trying to achieve here is our custom plugin to be part of that method list too. So a jQuery plugin is basically a customized method added to the jQuery prototype object.

The body of the HTML page we construct below consists of just one element <quote/> with some text in it. We give our plugin the name underline, and define it as $.fn.underline

					
					<!DOCTYPE html>
					<html lang="en">
					<head>
						<title>jQuery Plugin</title>	
						<script type="text/javascript" 
							src="//code.jquery.com/jquery-latest.min.js">
						</script>
					</head>
					<body>
						<quote>Computers make excellent and efficient servants, 
							but I have no wish to serve under them.</quote>

					    <script type="text/javascript">
					    	$(document).ready(function(){
								$.fn.underline = function() {
								   this.css( "border-bottom", "1px solid #000" );	
								};
								 
								$("quote").underline(); 
							});
					    </script>
					</body>
					</html>
					
				

Inside the script, the <quote/> element is selected and the plugin is applied on it. On page load, the text inside the <quote/> element is underlined.

jquery plugin

And to confirm what I preach, type

					
						$.fn.
					
				

in the browser's console, and you will find our newly defined plugin underline() showing up among the list of object methods.

jquery prototype underline

Resolving Conflicts

Now jQuery is not the only JavaScript library using $ as a variable; many other libraries like MooTools, Velocity.js also use it. So using them along with jQuery would cause conflicts in the code. For such purposes, jQuery came up with the jQuery.noConflict() method which releases the control of $ for the other libraries.

But again, this would require replacing all the $ references inside the plugin. To make it work both ways, without causing conflicts and still retain the use of $, the entire plugin needs to be wrapped inside a self-invoking function where $ is set as parameter and jQuery is passed as the arugument.

					
					<script type="text/javascript">
						$(document).ready(function(){
							(function ( $ ) {
								$.fn.underline = function() {
								   this.css( "border-bottom", "1px solid #000" );	
								};
							}(jQuery));
							 
							$("quote").underline(); 
						});
					</script>	
					
				

jQuery Plugin w/ Options

Plugins are useful when they are customizable by passing the desired options. Options generally consist of property-value pairs passed as an object literal.

We modify our underline() plugin below to accept few options to customize the thickness, colour and style of the underline. The options here are actually the declaration block of a typical CSS selector.

The options are passed as an object literal to change the colour, style and thickness of the underline, which is then merged into the default object inside the $.extend() method.

					
					<script type="text/javascript">
						$(document).ready(function(){
							(function ( $ ) {
								$.fn.underline = function(options) {
									let settings = $.extend({
							            color: "#000",
							            style: "solid",
							            width: "1px"
							        }, options );

									return this.css({
									   	"border-bottom-width": settings.width,
									   	"border-bottom-style": settings.style,
									   	"border-color": settings.color
									});
								};
							}(jQuery));

							$("quote").underline({
								color: "crimson",
								style: "dotted",
								width: "2px"
							});
						});
					</script>	
					
				

The three properties border-bottom-width, border-bottom-style and border-color can be replaced with the short-hand property border-bottom as shown below:

					
					<script type="text/javascript">
						$(document).ready(function(){
							(function ( $ ) {
								$.fn.underline = function(options) {
									let settings = $.extend({
							            color: "#000",
							            style: "solid",
							            width: "1px"
							        }, options );

							        let rule = settings.width + " " 
							        	+ settings.style + " " 
							        	+ settings.color;

									return this.css({			
									   	"border-bottom": rule
									});
								};
							}(jQuery));

							$("quote").underline({
								color: "crimson",
								style: "dotted",
								width: "2px"
							});
						});
					</script>	
					
				

Our newly customized underline now looks like

jquery plugin with options

Now you may wonder, why use $.extend()? That is because, not always will we be passing all the options. Passing just one option to the plugin as follows should also work.

					
						$("quote").underline({
							color: "aqua"
						});		
					
				

Loading a jQuery Plugin

Now that we have created a jQuery plugin, we will load it like any other plugin. We put the entire code within the self-invoking function in a separate file which we name as underline.js.

					
						(function ( $ ) {
							$.fn.underline = function(options) {
								let settings = $.extend({
						            color: "#000",
						            style: "solid",
						            width: "1px"
						        }, options );

								return this.css({
								   	"border-bottom-width": settings.width,
								   	"border-bottom-style": settings.style,
								   	"border-color": settings.color
								});
							};
						}(jQuery));
					
				

If underline.js is placed inside some /js directory, we first include it inside the document (as we do any other JavaScript file) and merely invoke the plugin as shown below.

					
					<!DOCTYPE html>
					<html lang="en">
					<head>
						<title>jQuery Plugin</title>	
						<script type="text/javascript" 
							src="//code.jquery.com/jquery-latest.min.js">
						</script>
						<script type="text/javascript" src="./js/underline.js">
						</script>
					</head>
					<body>
						<quote>Computers make excellent and efficient servants, 
							but I have no wish to serve under them.</quote>

					    <script type="text/javascript">
					    	$(document).ready(function(){
								$("quote").underline({
									color: "crimson",
									style: "dotted",
									width: "2px"
								}); 
							});
					    </script>
					</body>
					</html>