Counting characters with the JavaScript KeyPress event

Wed, Jul 28, 2010 - 3:38pm -- Isaac Sukin

Update: It turns out that this still isn't the best way to count characters in JavaScript. Updated post here.

I wrote the character counter for my Facebook-style Statuses module a long time ago. I originally wrote it using the "onKeyPress" JavaScript event, but that had problems with pressing non-letter keys, so I switched to using the "onKeyUp" event and never looked back. But this week a new issue appeared in my queue rightly pointing out that the character counter doesn't update while a key is being held down, even though new letters are being added to the textbox. So (with much more knowledge and experience under my belt this time) I dove back in and investigated. Here's what I found: the keypress event is called at an awkward time, when symbols for e.g. the backspace key are still being processed as part of the length of the string in the textarea but before they get processed as the removal of a character.

Solving this turned out to be simple: adding just a short delay before counting the characters gives the system enough time to properly update the string length.

Here's the phenomenon in action (type in the box to see the counters update):

No timer: 0
10ms delay: 0

Strange but true.