Is there any way to find out if the user pressed the percent key or 5 number? It has the same keycode in FireFox.
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.
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.
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