Skip to content

Instantly share code, notes, and snippets.

@jstarrdewar
Created February 5, 2012 04:50
Show Gist options
  • Save jstarrdewar/1742886 to your computer and use it in GitHub Desktop.
Save jstarrdewar/1742886 to your computer and use it in GitHub Desktop.
Limit the length of a textarea tag with a little bit of jQuery.
/**
* @author John Starr Dewar
*/
var textarea = $('textarea')[0];
var $counter = $('#counter');
var limit = 140;
$(textarea).keydown(function(event) {
switch (event.keyCode) {
case 8:
// backspace
case 46:
// forward delete
case 37:
// left arrow
case 38:
// up arrow
case 39:
// right arrow
case 40:
// down arrow
case 86:
// v (as in ctrl-v or command-v)
break;
default:
if (this.value.length == limit) {
event.preventDefault();
}
}
});
$(textarea).on('paste', function() {
setTimeout(function() {
if (textarea.value.length > limit) {
textarea.value = textarea.value.substr(0, limit);
displayLength();
}
}, 600);
});
$(textarea).keyup(displayLength);
function displayLength() {
if (textarea.value.length > limit) {
$counter.text("Too long!");
} else {
$counter.text(limit - textarea.value.length);
}
}
displayLength();
<!-- simple html to test limiting the text area length -->
<textarea id="tweet" cols="36" rows="4"></textarea>
<div id="counter"></div>
@jstarrdewar
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment