tags:

views:

133

answers:

3

Is there anyway around this?

If i pressed 'St', by the time i had pressed the t, if i were to output the input textfield.value in the onkeypress/onkeyup/etc function, i would only get 'S'??

How do i get rid of this lag?

+3  A: 

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

lincolnk
Strange that @Tom suggests to already having tried "onkeyup" ?
w3d
I'd suggest he's not tried it correctly then.
Tim Down
*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
A: 

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

NawaMan
+3  A: 

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
+1 for *window.setTimeout()*, using a delay of 0ms is enough to have the code execute immediately after the input is updated.
Andy E
@Andy: Very nice tip. Works in (almost) every browser?
Marcel Korpel
@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
Andy E: Resig's article doesn't mention timers with a delay of zero.
Tim Down
@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
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