Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onkeydown percent or five number

Is there any way to find out if the user pressed the percent key or 5 number? It has the same keycode in FireFox.

like image 933
Camilo Salas Avatar asked Dec 02 '22 21:12

Camilo Salas


2 Answers

You can check for modifier keys provided by the event object. event.shiftKey is for your specific use case. In addition there are the event.altKey, event.ctrlKey and event.metaKey (for windows key in windows and command key in MAC keyboards) properties of the event. In a code example you would have to perform the check inside your keyCode handler:

var NUMBER_FIVE = 53;
element.onkeydown = function (event) {
    if (event.keyCode == NUMBER_FIVE) {
        if (event.shiftKey) {
            // '%' handler
        } else {
            // '5' handler
        }
    }
};

In addition when using event.keyCode you are handling what the user pressed on the keyboard. If you want to be checking for specific ASCII characters then you can use event.charCode instead because this event property tells you what character the user is inputting instead of telling you what the user is pressing on the keyboard. Here's a complete guide for this on quirksmode.

like image 96
Konstantin Dinev Avatar answered Dec 10 '22 12:12

Konstantin Dinev


If you use keydown, 5 and % are the same keyCode. The event object also has a shiftKey boolean property that will tell you if the user is holding shift.

document.onkeydown = function (e) {
    if (e.keyCode === 53) {
        if (e.shiftKey) {
            // they pressed %
        } else {
            // they pressed 5
        }
    }
};

If you want to use keypress, they are two different keyCodes:

document.onkeypress = function (e) {
    if (e.keyCode === 53) {
        // they pressed 5
    }

    if (e.keyCode === 37) {
        // they pressed %
    }
};

This site is good for testing keyCodes.

like image 31
jbabey Avatar answered Dec 10 '22 12:12

jbabey