18

If I type 'St', by the time I press the t, if I output the input of textfield.value in the onkeypress/onkeydown functions, I only get 'S'.

Why is this? How do I get rid of this lag?

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Tom
  • 215
  • 1
  • 2
  • 5

3 Answers3

26

use the keyup event instead of keypress. keydown will show the before-keystroke value, as will keypress (apparently).

lincolnk
  • 11,218
  • 4
  • 40
  • 61
  • 2
    Strange that @Tom suggests to already having tried "onkeyup" ? – MrWhite Aug 17 '10 at 13:20
  • 3
    *keyup* will only fire when the key is released, it won't fire for repeated keystrokes. So if you're holding down the key to enter more than one of the same character, keyup won't fire until after the key is released. – Andy E Aug 17 '10 at 13:23
11

Within the keypress event, it's still possible to prevent the typed character from registering, so the input's value canot be updated until after the keypress event. You can use the keyup event instead, or use window.setTimeout() to set up a delay.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • +1 for *window.setTimeout()*, using a delay of 0ms is enough to have the code execute immediately after the input is updated. – Andy E Aug 17 '10 at 13:26
  • @Andy: Very nice tip. Works in (almost) every browser? – Marcel Korpel Aug 17 '10 at 13:29
  • 1
    @Marcel: it will work the same in every browser. I recommend reading J Resig's [How JavaScript timers work](http://ejohn.org/blog/how-javascript-timers-work/) for more detail on the subject. – Andy E Aug 17 '10 at 14:12
  • Andy E: Resig's article doesn't mention timers with a delay of zero. – Tim Down Aug 17 '10 at 14:28
  • 2
    @Tim: no, but it goes into detail on how timers work (queuing, specifically). It makes sense that a timer with 0ms would be added to the callback queue immediately. Specifically, from the recap section, *"If a timer is blocked from immediately executing it will be delayed until the next possible point of execution"*. Because of the single threaded nature, the next possible point of execution for a 0ms timer is when the thread would have become idle. – Andy E Aug 17 '10 at 14:59
  • Yes, I've read the article, and others. I mentioned it because I seemed to remember reading something somewhere about different behaviour in `setTimeout` with a zero delay, although I can't now find it. – Tim Down Aug 17 '10 at 15:20
1

Because the keystroke is not registered until keyup event occurs. So you should detect onkeyup event instead of onkeypress.

NawaMan
  • 25,129
  • 10
  • 51
  • 77