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