Skip to content

Instantly share code, notes, and snippets.

@EvanKrall
Created February 20, 2011 01:09
Show Gist options
  • Select an option

  • Save EvanKrall/835574 to your computer and use it in GitHub Desktop.

Select an option

Save EvanKrall/835574 to your computer and use it in GitHub Desktop.
Shows the number of characters remaining in a textarea.
<html>
<head>
<style>
.empty {
color: green;
}
.almostfull {
color: yellow;
}
.full {
color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function() {
var maxChars = 140;
var field = $('#field');
var counter = $('#counter');
var handler = function(event) {
var remainingChars = maxChars - field.val().length;
counter.text(remainingChars);
if (remainingChars >= maxChars/2) {
counter.attr('class', 'empty');
} else if (remainingChars >= 0) {
counter.attr('class', 'almostfull');
} else {
counter.attr('class', 'full');
}
};
field.keydown(handler).keyup(handler);
handler();
});
</script>
</head>
<body>
<textarea id="field"></textarea>
<span id="counter" />
</body>
</html>
@EvanKrall
Copy link
Author

This won't update if you modify the text without using the keyboard.

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