Is there a way to detect if a key is currently down in JavaScript?
I know about the "keydown" event, but that's not what I need. Some time AFTER the key is pressed, I want to be able to detect if it is still pressed down.
P. S. The biggest issue seems to be that after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend. Hopefully there is just a simple isKeyDown(key) function, but if not then this issue will need to be overcome / worked around.
Best Answer
In addition to using
keyup
andkeydown
listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.This are available on all browser generated event objects, such as those from
keydown
,keyup
, andkeypress
, so you don't have to use mousemove.I tried generating my own event objects with
document.createEvent('KeyboardEvent')
anddocument.createEvent('KeyboardEvent')
and looking fore.shiftKey
and such, but I had no luck.I'm using Chrome 17 on Mac