If your code is running in response to a keyboard event, you will be fine because all event handling functions are automatically passed an object representing the event that invoked it and that event object contains properties that have more information about the event that took place.
In your case, your Miscari
function was set up to receive the event via the argument e
, but the event needs to be triggered by something for the event to be generated and passed to your function.
I have modified my code to work like you say you have your code set up, that is when the document receives a keydown. Just activate the snippet area below with a click and then press any keys.
// This line will register the Miscari function as a keydown event handling
// function when keys are pressed down while document is in focus.
document.addEventListener('keydown', Miscari);
function Miscari(e) {
var x = e.keyCode;
switch (x) {
case 37:
dir="left";
break;
case 39:
dir="right";
break;
case 38:
dir="up";
break;
case 40:
dir="down";
break;
}
console.log(x);
}
solved Cannot read property ‘keyCode’ of undefined [closed]