Count Textarea Characters with JavaScript

I've been playing around with the Twitter API lately and, as you know, Tweets can only be 140 characters long. I wanted to use a textarea element, not an input type="text", so I couldn't just use maxchars to limit the number of characters. Additionally, I get annoyed when my text is chopped off when pasting. So, what to do? Well, I thought, why not make a little character counter like the one you find on the actual Twitter?

The first step is to create the JavaScript function. I placed mine in a file called count-chars.js and it looks like this:

function countChars(textbox, counter, max) {
  var count = max - document.getElementById(textbox).value.length;
  if (count < 0) { document.getElementById(counter).innerHTML = "<span style=\"color: red;\">" + count + "</span>"; }
  else { document.getElementById(counter).innerHTML = count; }

textbox and counter are the IDs of the elements of the textarea we're counting and the span where the count is going to go, respectively.

There's lots you can customize there. You could disable the form if too many characters are entered or you could automatically truncate the text. But, I prefer to just have the warning show up in red text.

The next step is to write the HTML itself:

<script type="text/javascript" src="/js/count-chars.js"></script>
<form action="#" method="post">
<p>Tweet Something: <span id="char_count"></span><br /><textarea name="tweet" id="textbox" class="form-control" rows="3" cols="60" onFocus="countChars('textbox','char_count',140)" onKeyDown="countChars('textbox','char_count',140)" onKeyUp="countChars('textbox','char_count',140)"></textarea></p>
<p><input type="submit" class="btn btn-primary" value="Tweet" /></p>

Hopefully, that's all pretty self-explanatory. You can change the 140 to be whatever character length you're looking for. (Make sure to change it in all 3 spots, though!)

Here's what the finished result looks like:

Tweet Something:

Nothing too fancy, for sure, but hopefully it will help. If you have questions or comments, let me know.



This post was published on February 26th, 2011 by Robert James Reese in the following categories: HTML and JavaScript Before using any of the code or other content in this post, you must read and agree to our terms of use.