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.
if you want to have the continious state use GetKey() this will return true as long as the key is pressed, GetKeyDown and GetKeyUp will only return true on the frame where the key is pressed down or gets released.
The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.
In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.
In addition to using keyup
and keydown
listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.
window.onmousemove = function (e) { if (!e) e = window.event; if (e.shiftKey) {/*shift is down*/} if (e.altKey) {/*alt is down*/} if (e.ctrlKey) {/*ctrl is down*/} if (e.metaKey) {/*cmd is down*/} }
This are available on all browser generated event objects, such as those from keydown
, keyup
, and keypress
, so you don't have to use mousemove.
I tried generating my own event objects with document.createEvent('KeyboardEvent')
and document.createEvent('KeyboardEvent')
and looking for e.shiftKey
and such, but I had no luck.
I'm using Chrome 17 on Mac
Is there a way to detect if a key is currently down in JavaScript?
Nope. The only possibility is monitoring each keyup
and keydown
and remembering.
after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend.
It shouldn't. You'll definitely get keypress
repeating, and in many browsers you'll also get repeated keydown
, but if keyup
repeats, it's a bug.
Unfortunately it is not a completely unheard-of bug: on Linux, Chromium, and Firefox (when it is being run under GTK+, which it is in popular distros such as Ubuntu) both generate repeating keyup-keypress-keydown sequences for held keys, which are impossible to distinguish from someone hammering the key really fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With