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.
My solution:
I can now check if any key is pressed anywhere else in the script by checking
If it's true, the key is pressed.
Look at this answer, and use
onkeyup
andonkeydown
. Here is more specific info about those events.if you press alt + enter, you will see the alert.
The following code is what I'm using:
When the user keeps holding down the Alt key for some time (about 2 seconds), a group of labels (class='key hidden') appears. When the Alt key is released, the labels disappear. jQuery and Bootstrap are both used.
I scanned the above answers and the proposed
keydown
/keyup
approach works only under special circumstances. If the user alt-tabs away, or uses a key gesture to open a new browser window or tab, then akeydown
will be registered, which is fine, because at that point it's impossible to tell if the key is something the web app is monitoring, or is a standard browser or OS shortcut. Coming back to the browser page, it'll still think the key is held, though it was released in the meantime. Or some key is simply kept held, while the user is switching to another tab or application with the mouse, then released outside our page.Modifier keys (
Shift
etc.) can be monitored viamousemove
etc. assuming that there is at least one mouse interaction expected when tabbing back, which is frequently the case.For most all other keys (except modifiers,
Tab
,Delete
, but includingSpace
,Enter
), monitoringkeypress
would work for most applications - a key held down will continue to fire. There's some latency in resetting the key though, due to the periodicity ofkeypress
firing. Basically, ifkeypress
doesn't keep firing, then it's possible to rule out most of the keys. This, combined with the modifiers is pretty airtight, though I haven't explored what to do withTab
andBackspace
.I'm sure there's some library out there that abstracts over this DOM weakness, or maybe some DOM standard change took care of it, since it's a rather old question.