Introduction
This article shows you how we can create a reusable JQuery plugin. In this article, we will create a JQuery plugin in a standalone JavaScript file which can be used in other projects when needed. The example used in this article is that of a CharacterCase
plugin. This plugin automatically converts user input into the desired letter case as and when the user types. After developing this plugin, we will implement it in a simple HTML web page. This web page will consist of text boxes which convert user input to either upper or lower case characters. In our plugin example, we will include a feature which allows end users to see characters being converted to the desired case while typing. This can be quite a nice feature as it helps you tell your users that there is nothing wrong with their keyboard!
Background
We write multiple lines of code to perform a simple task. We do this quite often across multiple projects. A good option we have in hand is to refractor this code into a reusable component such as a JQuery plugin. If we are able to do this, we can save a lot on our development time as well as efforts. By creating a reusable component, we can develop our own library of plugins. The aim of this article is to show you that creating JQuery plugin is easy and effective.
Using the Code
Creating the CharacterCase Plugin
- We begin by creating a new JavaScript file. Write the following code and save it as "CharacterCase-1.0.0.js".
(function ($) {
}(jQuery));
This code specifies the document ready event which is fired when the web browser loads the web page.
- Next, create a function to initialise a HTML text box. In our example, we will name our function,
SetCase()
.
$.fn.SetCase = function (options) {
}
After we have developed this function, we can implement this plugin in our web page and make use of the statement, $("#txtFullName").SetCase()
to initialise that text box.
- Within our
SetCase
function, specify the following defaults for variables and plugin options.
var upperValue = "UPPER";
var lowerValue = "LOWER";
var settings = $.extend({
charCase: upperValue,
showCaseChange: false,
showLog:true
}, options);
The settings plugin options initialises the plugin with default option values. For example, when we write, $("#txtFullName").SetCase()
, the text box is automatically initialised with "charCase
" property set to "UPPER" case characters. Which means, the text box will convert user input to upper case characters when no options are specified. To setup the text box to make use of lower case characters, we will have to initialise our text box using, $("#txtFullName").SetCase({ charCase: "lower" })
.
The showCaseChange
option enables the plugin to show characters being converted to the desired case as and when the user types it. Finally, the showLog
option displays error messages and warnings in the web browser's console for the developer.
- We will now write code to implement our
showCaseChange
feature. As described before, this nice little feature allows the user to see the characters being converted to the desired case as and when it is typed. To achieve this, we make use of a simple CSS trick. Write the following code immediately after writing the $.extend()
statement in the previous code snippet.
if (settings.showCaseChange == false) {
if (settings.charCase.toUpperCase() == upperValue) {
$(this).css("text-transform", "uppercase");
}
else if (settings.charCase.toUpperCase() == lowerValue) {
$(this).css("text-transform", "lowercase");
}
}
When the showCaseChange
is initialised to false
, we apply "text-transform
" CSS to our text box. When this CSS is applied, the user will automatically see the desired case at the first instance. When the showCaseChange
is set to true
, the user for example will be able to see a small character being converted to an upper case while typing. This is possible by making use of keyup
event to convert our characters which we will see next.
- Finally, we will write our core logic to convert user input to a desired case. Write the following code immediately after the
showCaseChange
logic.
$(this).keyup(function () {
var startIndex = this.selectionStart;
var endIndex = this.selectionEnd;
if (settings.charCase.toUpperCase() == upperValue) {
$(this).val($(this).val().toUpperCase());
}
else if (settings.charCase.toUpperCase() == lowerValue) {
$(this).val($(this).val().toLowerCase());
}
this.setSelectionRange(startIndex, endIndex);
return this;
});
The keyup
function does the actual work of converting the text box content into the desired character case using toUpperCase()
and toLowerCase()
functions. You will notice that we are keeping track of the cursor position and selection by making use of startIndex
and endIndex
variables. After we have converted the text to the desired character, we will reset the position of the cursor. If the user starts typing in between an already typed text, the cursor will jump to the end of the text box. Keeping a track of the cursor location helps avoid this issue.
- To make our plugin developer friendly, we can add additional logic to log error messages and warnings. These messages would be displayed in the console window of the web browser. The complete code for our plugin has been provided below:
(function ($) {
$.fn.SetCase = function (options) {
var upperValue = "UPPER";
var lowerValue = "LOWER";
var settings = $.extend({
charCase: upperValue,
showCaseChange: false,
showLog:true
}, options);
if (typeof settings.charCase === "undefined"
|| (settings.charCase.toUpperCase() != upperValue
&& settings.charCase.toUpperCase() != lowerValue))
{
if (settings.showLog)
{
console.log("CharacterCase Plugin: Invalid \"charCase\"
value provided. Valid values are \"" +
upperValue + "\" and \"" + lowerValue + "\".
Resetting value to \"" + upperValue + "\".");
}
settings.charCase = upperValue;
}
if (typeof settings.showCaseChange !== "boolean")
{
if (settings.showLog) {
console.log("CharacterCase Plugin: Invalid \"showCaseChange\"
value provided. Valid values are true and false. Resetting value to false.");
}
settings.showCaseChange = false;
}
if (typeof settings.showLog !== "boolean") {
if (settings.showLog) {
console.log("CharacterCase Plugin: Invalid \"showLog\"
value provided. Valid values are true and false. Resetting value to true.");
}
settings.showLog = true;
}
if (settings.showCaseChange == false) {
if (settings.charCase.toUpperCase() == upperValue) {
$(this).css("text-transform", "uppercase");
}
else if (settings.charCase.toUpperCase() == lowerValue) {
$(this).css("text-transform", "lowercase");
}
}
$(this).keyup(function () {
var startIndex = this.selectionStart;
var endIndex = this.selectionEnd;
if (settings.charCase.toUpperCase() == upperValue) {
$(this).val($(this).val().toUpperCase());
}
else if (settings.charCase.toUpperCase() == lowerValue) {
$(this).val($(this).val().toLowerCase());
}
this.setSelectionRange(startIndex, endIndex);
return this;
});
}
}(jQuery));
Implementing the CharacterCase Plugin
You can either make use of the JavaScript file we just developed, or you can also make use of a minified version of this plugin. Minified file version, CharacterCase-1.0.0.min.js has been bundled with this article. A demo implementation has also been included.
- First, create an HTML page with the basic structure and include the JQuery and the Plugin JavaScript files in your page. To use this plugin, you will need to include JQuery file as well. We will make use of the minified version in this example.
<!-- JQuery JavaScript -->
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<!-- CharacterCase JavaScript -->
<script src="CharacterCase/CharacterCase-1.0.0.min.js"></script>
Notice that the plugin JavaScript file has been placed inside the CharacterCase
folder within the root folder.
- Next, create three HTML text boxes. We will initialise these text boxes with our
CharacterCase
plugin.
Convert to Upper Case 1: <input type="text" id="txtUpperCase1" /><br />
Convert to Upper Case 2: <input type="text" id="txtUpperCase2" /><br />
Convert to Lower Case: <input type="text" id="txtLowerCase" />
- Finally, initialise these text boxes by calling
SetCase()
within the <font face="Courier New"><script></font>
tag.
<script type="text/javascript">
$(function () {
$("#txtUpperCase1").SetCase();
$("#txtUpperCase2").SetCase({ showCaseChange: true });
$("#txtLowerCase").SetCase({ charCase: "lower" });
});
</script>
In this code snippet, the first text box makes use of function, SetCase()
which will default the text to Uppercase
characters. You could have also specified SetCase({ charCase: "upper" })
. The second text box has been initialised with showCaseChange: true
. This option allows the user to see characters being converted to Uppercase
while typing. The last text box has been initialised to convert all its text to lowercase characters.
History
- 12th April, 2015: Initial version