When the user presses the single quote key, the e.keyCode property is zero, and the e.which property is 39. Executing String.fromCharCode(39) returns a single quote.
You want the keyCode if that property is in the event object:
var keycode = "keyCode" in e ? e.keyCode : e.which; That way you get zero for the keyCode when that property exists in the event object, and when the which property also exists.
document.onkeypressonkeydown = function(event) { event = event || window.event; var keyCode = "keyCode" in event ? event.keyCode : event.which; switch (keyCode) { case 37: console.log("37 was pressed", event); break; case 39: console.log("39 was pressed", event); break; } }; Edit #1: Other commenters and answers are correct. I forgot you shouldn't be detecting control keys with keypress events. Changed to onkeydown.
Full HTML example that works cross browser:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Key Codes Test</title> </head> <body> <script type="text/javascript"> document.onkeydown = function(event) { event = event || window.event; var keyCode = "keyCode" in event ? event.keyCode : event.which; switch (keyCode) { case 37: console.log("37 was pressed", event); break; case 39: console.log("39 was pressed", event); break; } }; </script> <input type="text" size="30"> </body> </html>