Reputation: 17256
I'm creating a text box for a user defined shortcut key combination, where it just prints out the modifiers and key.
I don't really care whether its set as you press or release the keys, so I started with the keypress
event. Firstly, modifiers seemed to affect the keycode (such as shift giving caps which implies keycode is not a key code at all but a typed character code) but also preventDefault
doesn't seem to work properly so I changed to keydown
. This introduced a discrepancy in event.keyCode. For example, comma ,
produced a delightful ascii keyCode=44
but now it's a disgusting keyCode=188
.
A test page: http://www.javascripter.net/faq/keyboardeventproperties.htm
I'd really like to have some standardized key codes here or at the very least some consistent ones. My request is for a workaround. Either:
What's the best way to get the printable character (ignoring modifiers, so ,
/<
are considered the same key and give ,
) for the weird but more consistent keydown
/keyup
?
Can keypress
be made more like keydown
/keyup
to actually give the key that was pressed and is there a mechanism like preventDefault
to stop the browser intercepting shortcuts?
Related: http://www.javascripter.net/faq/keycodes.htm
Upvotes: 1
Views: 3352
Reputation: 17256
For the moment, I'm just going to use keydown
and a modified version of this: http://www.javascripter.net/faq/fromkeycode.js
function fromKeyCode(n) {
if( 47<=n && n<=90 ) return unescape('%'+(n).toString(16))
if( 96<=n && n<=105) return (n-96).toString()
if(112<=n && n<=135) return 'F'+(n-111)
if(n==8) return 'Backspace'
if(n==9) return 'Tab'
if(n==13) return 'Enter'
if(n==16) return 'Shift'
if(n==17) return 'Ctrl'
if(n==18) return 'Alt'
if(n==19) return 'Pause'
if(n==20) return 'Caps_lock'
if(n==27) return 'Esc'
if(n==32) return 'Space'
if(n==33) return 'Page_up'
if(n==34) return 'Page_down'
if(n==35) return 'End'
if(n==36) return 'Home'
if(n==37) return 'Left'
if(n==38) return 'Up'
if(n==39) return 'Right'
if(n==40) return 'Down'
if(n==42) return '*' //Opera
if(n==43) return '+' //Opera
if(n==45) return 'Insert'
if(n==46) return 'Delete'
if(n==91) return 'Meta'
if(n==92) return 'Meta'
if(n==106) return '*'
if(n==107) return '+'
if(n==109) return '-'
if(n==110) return '.'
if(n==111) return '/'
if(n==144) return 'Num_lock'
if(n==145) return 'Scroll_lock'
if(n==186) return ';'
if(n==187) return '='
if(n==188) return ','
if(n==189) return '-'
if(n==190) return '.'
if(n==191) return '/'
if(n==192) return '\`'
if(n==219) return '['
if(n==220) return '\\'
if(n==221) return ']'
if(n==222) return '\''
if(n==224) return 'Meta'
return ""
}
Upvotes: 1