KeyDown To Character Or Function

JavaScript keydown event handler that converts the event to a Character, supports Upper case, Lower case, punctuation, etc. It also makes identifying and reacting to non-printables (ESC, Arrows, Function Keys, etc.) very simple.

HTML

<div id="test" style="border:1px solid red;width:200px;height:20px;font-size:20px;"></div>
<p>Be sure to click in THIS PANE before trying to type!  </p>
<p>Otherwise, you'll be typing in the HTML, CSS, or JavaScript panes.</P>
<P>Try typing mixed case letters, punctuation, and the Esc key.</p>

JavaScript

window.ele=document.getElementById("test");

// This catches keys from a physical keyboard, a soft keyboard on a tablet, or a
// scanner attached via USB
keyDownHandler = function keyDownHandler(e) {
	// keyboardCharMap is an array of arrays, with each inner
	// array having 2 columns - un-shifted, and shifted values.
	// iCol = 0 is the un-shifted value, while iCol=1 is the shifted value.
    // See the "keyboardCharMap", below, for printable characters.  
    // MODIFY keyboardCharMap to suit your needs if you want 
    //    more/less/different characters to be considered "printable".
	var iCol = 0;
	if (e.shiftKey) {
		iCol = 1;
	}
	var ch = keyboardCharMap[e.keyCode][iCol];
	if (ch!= "") {
		window.ele.innerHTML = window.ele.innerHTML + ch;
	}
    else{
    	// Optionally do things with non-printables, 
        // like CR, ESC, Backspace, LF, Tab, Arrows, F1-F24, etc.
        // See the arrary "keyboardNameMap", below, for possible keys.
        console.log("Empty...")
        var cmd = keyboardNameMap[e.keyCode];
        console.log("cmd: '" + cmd + "'"); 
        switch(cmd){
        	case "ESCAPE":
            	window.ele.innerHTML = window.ele.innerHTML + "-[Hit Esc!]-";
                break;
            ///...and so on...
        }
    }
};
document.onkeydown = keyDownHandler;

// names of known key codes (0-255)
var keyboardNameMap = [
  "", // [0]
  "", // [1]
  "", // [2]
  "CANCEL", // [3]
  "", // [4]
  "", // [5]
  "HELP", // [6]
  "", // [7]
  "BACK_SPACE", // [8]
  "TAB", // [9]
  "", // [10]
  "", // [11]
  "CLEAR", // [12]
  "ENTER", // [13]
  "ENTER_SPECIAL", // [14]
  "", // [15]
  "SHIFT", // [16]
  "CONTROL", // [17]
  "ALT", // [18]
  "PAUSE", // [19]
  "CAPS_LOCK", // [20]
  "KANA", // [21]
  "EISU", // [22]
  "JUNJA", // [23]
  "FINAL", // [24]
  "HANJA", // [25]
  "", // [26]
  "ESCAPE", // [27]
  "CONVERT", // [28]
  "NONCONVERT", // [29]
  "ACCEPT", // [30]
  "MODECHANGE", // [31]
  "SPACE", // [32]
  "PAGE_UP", // [33]
 ...