Skip to content

Instantly share code, notes, and snippets.

@rhowardiv
Created December 14, 2011 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhowardiv/1478433 to your computer and use it in GitHub Desktop.
Save rhowardiv/1478433 to your computer and use it in GitHub Desktop.
jQuery plugin for word / character counting
/*
* Character Count Plugin - jQuery plugin
* Dynamic character count for text areas and input fields
* written by Alen Grakalic
* http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas
* and Richard Howard, Roubini Global Economics
* http://www.roubini.com
*
* Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* Built for jQuery library
* http://jquery.com
*
*/
(function($)
{
$.fn.charCount = function (userOptions)
{
var defaults = {
type: 'char', // or 'word'
allowed: 140,
warning: 25,
css: 'counter',
counterElement: 'span',
cssWarning: 'warning',
cssExceeded: 'exceeded',
counterText: '',
contentCall: function (content) { return content; }
},
options = $.extend(defaults, userOptions)
;
function makeCalc(self, counter)
{
return function calculate() {
var v = options.contentCall(self.val()),
count = (options.type === 'word' && v.length > 0)
? v.replace(/^\s+|\s+$/g).split(/\s+/).length
: v.length,
available = options.allowed - count;
if (available <= options.warning && available >= 0){
counter.addClass(options.cssWarning);
} else {
counter.removeClass(options.cssWarning);
}
if (available < 0){
counter.addClass(options.cssExceeded);
} else {
counter.removeClass(options.cssExceeded);
}
counter.html(options.counterText + available);
};
}
this.each(function () {
var self = $(this),
counter = $(
'<'+ options.counterElement +' class="' + options.css + '">'
+ options.counterText +'</'+ options.counterElement +'>'
).insertAfter(self),
calc = makeCalc(self, counter)
;
calc();
self.bind('keyup change', calc);
});
};
}(jQuery));
@rhowardiv
Copy link
Author

A sample contentCall function is provided at https://gist.github.com/1478461

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment