Skip to content

Instantly share code, notes, and snippets.

@peterjwest
Created August 16, 2012 09:08
Show Gist options
  • Save peterjwest/3368643 to your computer and use it in GitHub Desktop.
Save peterjwest/3368643 to your computer and use it in GitHub Desktop.
Text limiter jQuery plugin
// Limits the number of characters in a textarea and displays characters remaining
// Accepts a jQuery element statusElem which displays how many characters are remaining
$.fn.textLimiter = function(statusElem, length) {
return this.each(function() {
var input = $(this);
var visible = true;
var initial = statusElem.text();
input.bind("keydown keyup paste input", function() {
var text = input.val();
if (text.length == 0) {
statusElem.text(initial);
if (!visible) statusElem.stop().animate({opacity: 1});
visible = true;
}
else if (text.length > 5) {
statusElem.text(Math.max(length - text.length, 0)+" characters left");
if (!visible) statusElem.stop().animate({opacity: 1});
visible = true;
}
else {
if (visible) statusElem.stop().animate({opacity: 0});
visible = false;
}
if (text.length > length) {
input.val(input.val().substr(0, length));
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment