The following script does what it should, that is, it reacts on the keys \"arrow left\" and \"arrow right\". However, due to a keycode clash, it reacts on a single quote as
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.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;
}
};
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:
Key Codes Test