Javascript/YUI Character Counter off by one
-
06-07-2021 - |
Question
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.......
Solution
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 the keypress
event is returned. This explains why the counter shows an outdated (inaccurate) number of characters left.
More about keydown
, keypress
, and keyup
events: http://www.quirksmode.org/dom/events/keys.html
UPDATE:
There is a better way to detect changes to <input>
and <textarea>
.
The YUI event-valuechange
module provides a valuechange
event that fires when the user changes the input value by:
- typing a simple character
- typing a multi-stroke character
- using an Input Method Editor
- cutting from or pasting into the value with Ctrl+X or Cmd+V
- cutting or pasting with a keyboard-summoned context menu; or
- cutting or pasting from the right-click context menu.
Here's how to use it on an input with ID message
:
YUI().use('event-valuechange', function (Y) {
Y.one('#message').on('valueChange', function (e) {
// The value has changed! Handle it here...
});
});
Live demo: http://jsfiddle.net/Pd9X9/
OTHER TIPS
Change to the keyup
event and it works fine for me here: http://jsfiddle.net/jfriend00/grZW7/. The keypress event only happens on some keys and may happen BEFORE the text of the field is updated whereas keyup
always happens afterwards.
Use 'keyup' as the event trigger