Created
March 10, 2011 11:27
-
-
Save paveltyk/863967 to your computer and use it in GitHub Desktop.
TwitCharCounter jQuery plugin
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
/*! | |
* jQuery TwitCharCounter Plugin | |
* version: 1.0 (10-MAR-2011) | |
* created by: PavelTyk | |
* | |
* This is a simple char counter plugin (like the Twitter one). It has flexible | |
* settings and allows minimize configuration settings. | |
* | |
* Examples and documentation at: https://gist.github.com/863967 | |
* Dual licensed under the MIT and GPL licenses: | |
* http://www.opensource.org/licenses/mit-license.php | |
* http://www.gnu.org/licenses/gpl.html | |
*/ | |
;(function($) { | |
/* | |
Usage Note: | |
----------- | |
HTML: | |
<textarea id="description"></textarea> | |
<p id="description_char_count">Maximum 300 characters</p> | |
JavaScript: | |
$(document).ready(function() { | |
$('#description').twit_char_counter(); | |
}); | |
Customization: | |
Available options are: limit, counter_text, counter_selector and color. | |
Defaults: | |
Limit: limit is equal to textarea "limit" attr if it present, otherway it set to 300. | |
Counter text: counter_text is equal to "{{available}} of {{limit}} characters left" | |
Counter selector: if textarea has an ID attr, then counter_selector is set to | |
"#" + textarea_id + "char_count", otherway it is "#char_count" | |
Color: by default equals to #ff0000 | |
*/ | |
$.fn.twit_char_counter = function(options) { | |
var counter_text_id = 'char_count' | |
if ($(this).attr('id').length > 0) { | |
var counter_text_id = $(this).attr('id') + '_' + counter_text_id; | |
} | |
var defaults = { | |
limit: $(this).attr('limit') > 0 ? $(this).attr('limit') : 300, | |
counter_text: "{{available}} of {{limit}} characters left", | |
counter_selector: '#' + counter_text_id, | |
color: "#f00" | |
}; | |
var options = $.extend(defaults, options); | |
var default_color = $(options.counter_selector).css('color'); | |
function calculate(obj) { | |
var selector = options.counter_selector; | |
var limit = options.limit; | |
var available = limit-obj.val().length; | |
$(selector).css('color', default_color); | |
if (obj.val().length >= limit) { | |
obj.val(obj.val().substr(0,limit)); | |
$(selector).css('color', options.color); | |
available = 0; | |
} | |
var counter_text = options.counter_text.replace("{{limit}}", limit).replace("{{available}}", available); | |
$(selector).html(counter_text); | |
}; | |
$(this).keyup(function(){calculate($(this));}); | |
$(this).change(function(){calculate($(this));}); | |
return $(this); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment