Object JavaScript – Building a Reusable Stateless jQuery Plugin

6327_image_58FAEDFAIn this post, you will learn step-by-step to build your own custom, reusable, testable jQuery Plugin.

There are times where you will want to reuse code that performs a series of operations on a selection.

For example, you may want to embed information a span element and then have that information displayed in a references section near the end of the document. In this case, the jQuery plugin is stateless.

In the next post, Building Stateful jQuery UI Plugin Using Widget Factory, you will see how to create a stateful jQuery plugin using jQuery Widget. And you will see how the widget is a better solution for plugins that require user interaction, because the Widget factory helps you maintain state.

Stateless Widgets

jQuery provides a lot of help for stateless widgets. For example:

.text( "hello" )

Here you are setting the text somewhere in the DOM and you do not need to maintain state. In fact, jQuery provides a way to create plugins.


$.fn.greenify = function() {
this.css( "color", "green" );
};
$( "a" ).greenify(); // Makes all the links green.

The jQuery plug-in documentation provides a good example for a simple use case (making links green).

In this post, you will learn one that is a bit more complex. You will learn step by step on how to build a jQuery footnote plugin. Interestingly, the footnote plugin does not require you to maintain state. In other words, you provide information regarding the plug in sate once, and it does not need to change.

Setting Up the First Use Case

First, you will need to create an HTML page and  start jQuery.

NOTE: For details on how to get jQuery and start jQuery for commercial product, see What is jQuery and How to Start using jQuery? and Load jQuery with Javascript and use jQuery. And in your ASP.NET projects, you will want to minify it.

For our purposes, we’ll add jQuery to a Visual Studio project using NuGet and then reference it from our project. And add some text.


<!DOCTYPE html>
<html>
<head>
<title>Footnoter</title>
</head>
<body>
<p id="myParagraph">
In up so discovery my middleton eagerness dejection explained. Estimating excellence ye contrasted
insensible as. Oh up unsatiable <span class="footnote">Unpacked reserved sir.</span> interested.
Present suppose in esteems indemesne colonel it to. End horrible she landlord screened stanhill.
Repeated offended <span class="footnote">you opinions off</span> dissuade ask packages screened.
She alteration everything sympathize impossible his get compliment. Collected few extremity
suffering met had sportsman.
</p>
<h2>References</h2>
<div id="#references"></div>
<script src="Scripts/jquery-2.1.3.js"></script>
<script src="Scripts/footnoter/jquery-footnoter-0.0.1.js"></script>
<script>
$("myParagraph").footnote();
</script>
</body>
</html>

Next, let’s define our first use case. Take the text in the .footnote span and make it red.

Protect jQuery

Put it into a file named jquery-footnoter-0.0.1.js in the Scripts/footnotes folder.

First, you will want your plugin to work well with others. To protect the $ alias used by JQuery and use it inside your plugin, you will want  to put all of your code inside of an Immediately Invoked Function Expression, and then pass the function jQuery, and name the parameter $:


(function ( $ ) {
// use $ in your code as the jQuery alias here
}( jQuery ));

Chaining

Next, let’s do something simple to be sure we have each of the footnote items. And be sure to return the items that are being manipulated so they can be chained to the next step. chaining gives your jQuery plugin the ability to add an additional feature.


(function ($) {
$.fn.footnote = function () {
console.log("footnote");
var footnotes = this.find("span.footnote");
footnotes.css("color", "red");
return footnotes;
};
}(jQuery));

In this case, you can return the footnote spans as the return value.

You can then chain the result to another value.


<script>
$("#myParagraph").footnote().css("background-color", "yellow");
</script>

view raw

chaining.html

hosted with ❤ by GitHub

Which results like this:

image

 

Moving Elements Around

You can use jQuery to reorder the elements in the DOM. When you write the code, you will want to understand that you are moving elements and not text.


(function ($) {
$.fn.footnote = function () {
// console.log("footnote");
var footnotes = this.find("span.footnote");
footnotes.each(function (key, value) {
//console.log("footnote" + key + " : " + $(value).contents().text());
var footnoteContentsNode = $(value).clone();
var footnoteNumberTextNode = document.createTextNode("[" + key + "] ");
$("#references").append(footnoteNumberTextNode).append(footnoteContentsNode).css("color", "blue").append("<br />");
$(value).text("[" + key + "] ").css("color", "blue").css("vertical-align", "super").css("font-size", "60%");
});
return footnotes;
};
}(jQuery));

image

Providing Options

But the plug-in is not really reusable. So far, it requires that the footnotes are blue and that they are appended to the #references div.


$.fn.footnote = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "blue",
referencesLocation: "#references"
}, options);
// use the options
$(settings.referencesLocation).css("color", settings.color);
//
return //..
}


$("#myParagraph").footnote({
color: "orange",
referencesLocation: "#theReferences"
});

Sample Code

The following is the sample code:


(function ($) {
$.fn.footnote = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "blue",
referencesLocation: "#references"
}, options);
var footnotes = this.find("span.footnote");
footnotes.each(function (key, value) {
//console.log("footnote" + key + " : " + $(value).contents().text());
var footnoteContentsNode = $(value).clone();
var footnoteNumberTextNode = document.createTextNode("[" + key + "] ");
// The default value for referencesLocation gets overridden by $.extend().
$(settings.referencesLocation).append(footnoteNumberTextNode).append(footnoteContentsNode)
.css("color", settings.color).append("<br />");
// The default value for color gets overridden by $.extend().
$(value).text("[" + key + "] ").css("color", settings.color)
.css("vertical-align", "super");
});
return footnotes;
};
}(jQuery));


<!DOCTYPE html>
<html>
<head>
<title>Footnoter</title>
</head>
<body>
<p id="myParagraph">
In up so discovery my middleton eagerness dejection explained. Estimating excellence ye contrasted
insensible as. Oh up unsatiable <span class="footnote">Unpacked reserved sir.</span> interested.
Present suppose in esteems indemesne colonel it to. End horrible she landlord screened stanhill.
Repeated offended <span class="footnote">you opinions off</span> dissuade ask packages screened.
She alteration everything sympathize impossible his get compliment. Collected few extremity
suffering met had sportsman.
</p>
<h2>References</h2>
<div id="references"></div>
<div id="theReferences"></div>
<script src="Scripts/jquery-2.1.3.js"></script>
<script src="Scripts/footnoter/jquery-footnoter-0.0.3.js"></script>
<script>
$("#myParagraph").footnote({
color: "orange",
referencesLocation: "#theReferences"
});
</script>
</body>
</html>

References


One thought on “Object JavaScript – Building a Reusable Stateless jQuery Plugin

Comments are closed.