I've gone over the code several times and can't figure out why the first keystroke doesn't seem to count.
When the textarea is an empty string, the counter display should read accurately. But it seems that the textarea needs to be empty twice.......
Try listening to the
keyup
event instead.The
keypress
event is fired when the actual character is being inserted in the textarea. When you read the value of the textarea —message.get('value')
, the old value before thekeypress
event is returned. This explains why the counter shows an outdated (inaccurate) number of characters left.More about
keydown
,keypress
, andkeyup
events: http://www.quirksmode.org/dom/events/keys.htmlUPDATE:
There is a better way to detect changes to
<input>
and<textarea>
.The YUI
event-valuechange
module provides avaluechange
event that fires when the user changes the input value by:Here's how to use it on an input with ID
message
:Live demo: http://jsfiddle.net/Pd9X9/