Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Multiple Keys to Keypress Event

I am currently using this Javascript keypress code to fire events upon keypress:

$(document).keydown(function(e) {
    switch(e.keyCode) {

    case 39:
        e.preventDefault();
        alert("Arrow Key");
        break;

    case 37:
        e.preventDefault();
        alert("Arrow Key");
    }
});

but what I am wondering is if I can instead of binding one key bind a combination of two keys. Could I possibly do something like:

$(document).keydown(function(e) {
    switch(e.keyCode) { 
        case 39 && 37:
            e.preventDefault();
            alert("Arrow Key");
        break;
    }
});
like image 305
mcbeav Avatar asked Nov 13 '10 16:11

mcbeav


People also ask

What is the difference between keypress () and Keydown ()?

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.

Is keypress deprecated?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

What is the use of Keydown event?

The onkeydown attribute fires when the user is pressing a key (on the keyboard).

How can I listen for keypress event on the whole page?

For this, you have to import HostListener in your component ts file. import { HostListener } from '@angular/core'; then use below function anywhere in your component ts file. @HostListener('document:keyup', ['$event']) handleDeleteKeyboardEvent(event: KeyboardEvent) { if(event.


2 Answers

If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).

You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.

Example:

$(document).keydown(function(e) {
    if(e.which == 98 && e.ctrlKey) {
        // ctrl+b pressed
    }
});
like image 104
ThiefMaster Avatar answered Sep 20 '22 02:09

ThiefMaster


Why not use if rather than switch?

$(document).keydown(function(e) {
    if ((e.keyCode === 37) || (e.keyCode === 39)) {
        e.preventDefault();
        alert("Arrow Key");
    }
});
like image 29
lonesomeday Avatar answered Sep 22 '22 02:09

lonesomeday