Check if a key is down? Check if a key is down? javascript javascript

Check if a key is down?


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.


My solution:

var pressedKeys = {};window.onkeyup = function(e) { pressedKeys[e.keyCode] = false; }window.onkeydown = function(e) { pressedKeys[e.keyCode] = true; }

I can now check if any key is pressed anywhere else in the script by checking

pressedKeys["code of the key"]

If it's true, the key is pressed.