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.
javascript
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.
