Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can jQuery .keypress() detect more than one key at the same time?

Is there a way for jQuery to detect that more than one key was pressed at the same time?

Is there any alternative that allows for pressing two keys at the same time to be detected?

like image 578
Chris Abrams Avatar asked Feb 10 '11 07:02

Chris Abrams


People also ask

What does keypress do in jQuery?

The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).

What is the difference between jQuery Change () and keypress () events?

The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.

What is the difference between keypress and Keydown?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What is Keyup and Keydown in jQuery?

jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.


2 Answers

In order to detect multiple keys being held down, use the keydown and keyup events.

var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;
});

$(document).keyup(function (e) {
    delete keys[e.which];
});

I've put together a demo here: http://jsfiddle.net/gFcuU/. It's kind of fun, though I noticed my keyboard is only able to detect at most 6 keys.

like image 188
David Tang Avatar answered Oct 21 '22 23:10

David Tang


It depends. For "normal" keys, that means Non- Shift, Ctrl, ALT, (CMD), the answer is no, the event handler will catch/fire in a queue, one after another.

For the modifier keys I mentioned above, there is a property on the event object.

Example:

$(document).bind('keypress', function(event) {
    if( event.which === 65 && event.shiftKey ) {
        alert('you pressed SHIFT+A');
    }
});

Jsfiddle demo.

Other propertys are:

  • event.ctrlKey
  • event.altKey
  • event.metaKey
like image 59
jAndy Avatar answered Oct 22 '22 00:10

jAndy