javascript - alert letters by name on pressing keyboard buttons without using a switch statement -
here have simple piece of code.i want alert letters [a-z] on pressing buttons on keyboard representing letters.till alerting keycodes.i know can whit switch statement.but large piece of switch statement. questions are:
1.is there way can alert every letters name on keypress without switch statement?
2.left,right,up,down arrow keys not alerting keycode numbers.why so??how can overcome problem??
(function(){ document.body.addeventlistener('keypress',function(e){ alert(e.keycode); }); })();
to show letters keycode:
alert (string.fromcharcode(e.keycode));
to address problems arrow-keys not showing keycode
s (37 - 40):
(function(){ document.body.addeventlistener('keyup',function(e){ // keycodes of arrow keys, matched appropriate // unicode arrow symbol: var directionals = { '38' : 8593, // string.fromcharcode(38) => & '39' : 8594, // string.fromcharcode(39) => ' '40' : 8595, // string.fromcharcode(40) => ( '37' : 8592 // string.fromcharcode(37) => % }, // if there falsey value directionals object, // use e.keycode unchanged; otherwise substitute // e.keycode above-supplied arrow-character: keycodetouse = !directionals[e.keycode] ? e.keycode : directionals[e.keycode]; // don't alerts; access console (in browsers) press 'f12': console.log(string.fromcharcode(keycodetouse)); }); })();
html, body { background-color: rgba(255,255,180, 0.5); height: 100%; }
the problem (for whatever reason) arrow keys return keycodes on keyup
, keydown
, not on keypress
. further, string.fromcharcode()
using key codes (as shown in javascript, above) return characters not, in fact, arrows. so, have use alternate unicode references (supplied above, in javascript).
references:
Comments
Post a Comment