Writing your first jQuery plugin: a character counter in 60 lines
A step-by-step tutorial for a reusable jQuery 1.4 plugin that counts characters in a textarea, with options, defaults and chaining.
Over the past few months I’ve written the same bit of JavaScript three times at the agency: a little counter under a <textarea> that shows how many characters you have left. For the sports club (max 500 characters for a match report), for the bakery (max 140 for the “message on the cake”) and last week for a law firm. Three times copy-paste, three times slightly different, three times a bug.
Time for a plugin, then. In this post I’ll build one step by step, with jQuery 1.4.2.
The skeleton#
A jQuery plugin is nothing more than a function on $.fn. Anything you hang on there can be called on a jQuery selection, just like .hide() or .css().
(function ($) {
$.fn.charCounter = function (options) {
return this.each(function () {
// the actual work happens here, once per element
});
};
})(jQuery);
Three things to watch out for:
- The
(function ($) { ... })(jQuery);wrapper. It lets you safely use$inside your plugin, even when the site callsjQuery.noConflict()because Prototype or MooTools is also on the page. At the agency that happens more often than you’d think. return this.each(...). Herethisis the jQuery selection. Returning it keeps chaining working:$('textarea').charCounter().addClass('ready').- Inside
each,thisis a plain DOM element, not a jQuery object. If you want jQuery methods, wrap it:$(this).
Options and defaults#
Every client wants something different: a different maximum, different text, the counter in a different place. That’s what $.extend is for:
$.fn.charCounter.defaults = {
max: 500,
text: '{left} characters left',
warnAt: 20,
className: 'counter',
warnClassName: 'counter-almost-full'
};
By putting the defaults publicly on $.fn.charCounter.defaults, someone can override them for a whole site without touching the plugin:
$.fn.charCounter.defaults.text = '{left} to go';
Inside the plugin you merge the defaults with whatever the caller passes in. Note the empty object as the first argument: without it you overwrite the defaults themselves, which is a bug you only notice on the second textarea on the same page. (Don’t ask me how I know.)
var settings = $.extend({}, $.fn.charCounter.defaults, options);
The full plugin#
(function ($) {
$.fn.charCounter = function (options) {
var settings = $.extend({}, $.fn.charCounter.defaults, options);
return this.each(function () {
var $field = $(this);
// don't initialise twice
if ($field.data('charCounter')) {
return;
}
var max = parseInt($field.attr('data-max'), 10) || settings.max;
var $counter = $('<div />', { 'class': settings.className });
$field.after($counter);
function update() {
var value = $field.val();
if (value.length > max) {
$field.val(value.substr(0, max));
value = $field.val();
}
var left = max - value.length;
$counter
.text(settings.text.replace('{left}', left))
.toggleClass(settings.warnClassName, left <= settings.warnAt);
}
$field.bind('keyup.charCounter change.charCounter', update);
$field.data('charCounter', { counter: $counter });
update();
});
};
$.fn.charCounter.defaults = {
max: 500,
text: '{left} characters left',
warnAt: 20,
className: 'counter',
warnClassName: 'counter-almost-full'
};
})(jQuery);
A few choices explained:
$('<div />', { 'class': ... })is new in jQuery 1.4: you can create an element and pass its attributes straight away.classis quoted because it’s a reserved word, and IE chokes on it as an unquoted key.data-maxlets you put the maximum in the HTML. Handy when one form has several fields with different limits. It’s not valid HTML 4, but browsers read it fine withattr().- Namespaced events (
keyup.charCounter). Later you can remove only your own handlers with$field.unbind('.charCounter'), without dragging along the handlers from some other plugin. .data()remembers that the field already has a counter. If you accidentally call the plugin twice (and that happens, trust me, especially in a WordPress theme with four plugins that all useready), you don’t get a double counter.
Usage#
<textarea name="report" data-max="500"></textarea>
<textarea name="cake" data-max="140"></textarea>
<script src="js/jquery-1.4.2.min.js"></script>
<script src="js/jquery.charcounter.js"></script>
<script>
$(document).ready(function () {
$('textarea[data-max]').charCounter({
warnAt: 10
});
});
</script>
And a bit of CSS:
.counter {
font-size: 11px;
color: #666;
text-align: right;
}
.counter-almost-full {
color: #c00;
font-weight: bold;
}
What’s still missing#
To be fair, there are edge cases:
- If someone pastes text with the right mouse button,
keyupnever fires.changeonly catches it when the field loses focus. You can also bind topastewith asetTimeoutof 0 ms, because the new value isn’t in the field yet at the moment the event fires. - Silently chopping off text isn’t exactly user-friendly. A better approach is to turn the counter red and let the server enforce the limit. The server has to do that anyway, because JavaScript can be switched off. I learned that one when a client got a 4000-character match report in their newsletter.
- Line breaks: in some browsers an Enter counts as one character in JavaScript but as two (
\r\n) when the form is posted. Your PHP side needs to account for that.
All in all: sixty lines, one file, and I never have to write it again. Next time a client wants a counter, it’s one line of code. That’s the best kind of lazy.