Created
August 16, 2012 09:08
-
-
Save peterjwest/3368643 to your computer and use it in GitHub Desktop.
Text limiter 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
// 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