Just to throw another hat in the ring. Determining characters in keypress events isn't something that JavaScript does very well right now. Due to it's variability, I'd rather not force any method to have to decipher it inline, and defer evaluation to another method that can be subbed in and out.
The ideal would be a method that takes in the KeyUp Event
as an argument and returns whatever character was pressed: Let's call it MapKeyPressToActualCharacter
.
Then your code could look super clean like this:
<!-- language: lang-js -->
$("#id").on("keyup", function(e){
switch(MapKeyPressToActualCharacter(e)) {
case "#":
//handle #
break;
case "@":
//handle @
break;
}
});
Now we just have to figure out how to write MapKeyPressToActualCharacter
.
Here's an implementation based off the answer to get key char from keycode with shift modifier:
<!-- language: lang-js -->
function MapKeyPressToActualCharacter(event) {
var isShiftKey = event.shiftKey;
var characterCode = event.keyCode;
var isAlphabetChar = characterCode >= 65 && characterCode <= 90;
var specialChars = [8,9,13,16,17,18,20,27,91,92];
var character = "";
if (valueInArray(characterCode, specialChars)) {
return false;
}
if (isAlphabetChar) {
character = String.fromCharCode(characterCode);
} else if (isShiftKey) {
character = GetShiftedCharacters()[characterCode];
} else {
character = String.fromCharCode(characterCode);
}
return character;
}
function valueInArray(value, array) {
return array.indexOf(value) > -1;
}
##Working Demo in Fiddle
You'll also need to get a mapping of each character and it's shifted corollary with the method GetShiftedCharacters
:
<!-- language: lang-js -->
function GetShiftedCharacters() {
var characterMap = {32: " ",
48: ")",
49: "!",
50: "@",
51: "#",
52: "$",
53: "%",
54: "^",
55: "&",
56: "*",
57: "(",
59: ":",
107: "+",
109: "_",
188: "<",
190: ">",
191: "?",
192: "~",
219: "{",
220: "|",
221: "}",
222: "\\" };
return characterMap;
}
###Here's a distributable JS file: MapKeyPress.js
*Note, since the MapKeyPress function calls array.indexOf
, you should use a polyfill to extend to older browsers. Here's a shiv called indexOfPolyFill.js, and here's an example.