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?
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).
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.
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.
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.
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.
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
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