Twitter-like character count

jQuery plugin: Simplest Twitter-like dynamic character count for textareas and input fields

by Tushar Thakare

HTML

<script type="text/javascript">
	$(document).ready(function(){	
		$("#message2").charCount({
			allowed: 50,		
			warning: 20,
			counterText: 'Characters left: '	
		});
    
    	$("#message3").charCount({
			allowed: 10,		
			warning: 2,
			counterText: '<br>Characters left: '	
		});
	});
</script>
<body>

   

            <textarea id="message2" name="message2"></textarea>
            
                <input id="message3" name="message2"></input>
 






</body>

CSS

.warning{color:#600;}	
.exceeded{color:#e00;}

JavaScript

(function($) {

	$.fn.charCount = function(options){
	  
		// default configuration properties
		var defaults = {	
			allowed: 140,		
			warning: 25,
			css: 'counter',
			counterElement: 'span',
			cssWarning: 'warning',
			cssExceeded: 'exceeded',
			counterText: ''
		}; 
			
		var options = $.extend(defaults, options); 
		
		function calculate(obj){
			var count = $(obj).val().length;
			var available = options.allowed - count;
			if(available <= options.warning && available >= 0){
				$(obj).next().addClass(options.cssWarning);
			} else {
				$(obj).next().removeClass(options.cssWarning);
			}
			if(available < 0){
				$(obj).next().addClass(options.cssExceeded);
			} else {
				$(obj).next().removeClass(options.cssExceeded);
			}
			$(obj).next().html(options.counterText + available);
		};
				
		this.each(function() {  			
			$(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
			calculate(this);
			$(this).keyup(function(){calculate(this)});
			$(this).change(function(){calculate(this)});
		});
	  
	};

})(jQuery);