Counting Characters in a Textarea with JavaScript

Tue, May 17, 2011 - 1:01am -- Isaac Sukin

About a year ago, I wrote about how I was using the JavaScript onKeyPress event to count the characters in a textarea. It turns out that among newer browsers, the trick I employed only works in Firefox. Other browsers (IE, Chrome, Safari, Opera) don't register keypress events for non-character keys like Control and Backspace. KeyUp and KeyDown have their own problems, but we can get around this by updating the character counter on both the KeyDown and KeyUp events. I've built a test below so that you can try it for yourself.

Things to try:

  • Typing characters in normally
  • Holding down a character
  • Hitting backspace
  • Cutting-and-pasting text
KeyPress, no delay: 0
KeyPress, 10ms delay: 0
KeyUp: 0
KeyDown: 0
KeyUp + KeyDown: 0

Why does this happen?

  • KeyPress with no delay checks the number of characters before the keystroke is processed.
  • KeyPress with a delay doesn't fire when non-character keys are pressed in most browsers, so the counter doesn't update when pressing e.g. Backspace.
  • KeyUp only updates the character counter when a key is released, so the counter doesn't update while a key is being held down.
  • KeyDown checks the number of characters before the keystroke is processed, like KeyPress with no delay.
  • KeyUp and KeyDown together work correctly. On normal keystrokes, KeyDown happens first and writes the wrong value -- but then KeyUp fires and writes the correct value. (You could optimize this by keeping track of the number of times KeyDown fires before KeyUp fires if you really wanted to.) When a key is held down, KeyDown updates the counter until the key is released and KeyUp registers the final value.