Created
December 14, 2011 20:47
-
-
Save rhowardiv/1478433 to your computer and use it in GitHub Desktop.
jQuery plugin for word / character counting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A sample contentCall function is provided at https://gist.github.com/1478461