Last active
August 29, 2015 14:13
-
-
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).
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
// 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