Skip to content

Instantly share code, notes, and snippets.

@gimesi
Last active August 29, 2015 14:13
Show Gist options
  • Save gimesi/34cac8a8728ec910771d to your computer and use it in GitHub Desktop.
Save gimesi/34cac8a8728ec910771d to your computer and use it in GitHub Desktop.
Snippet to count how many characters are left in a textarea. I use it in the backend of a CMS to insert meta information for social shares (e.g. re-tweets).
// in HTML:
// <div id="count"></div>
// <textarea id="#share-description"></textarea>
$(document).ready(function() {
var chars = 115; // 140 minus 25 (Twitter links (24 chars) plus 1 whitespace)
var left;
if ($("#share-description").val().length === 0) {
left = chars;
} else {
left = chars - $("#share-description").val().length;
}
$("#count").append("Characters left: " + left);
$("#share-description").keyup(function () {
if ($(this).val().length > chars) {
$(this).val($(this).val().substr(0, chars));
}
var left = chars - $(this).val().length;
$("#count").html("Characters left: " + left);
if (left <= 12) {
$("#count").css("color", "#c00");
} else {
$("#count").css("color", "#000");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment