Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  118] [ 6]  / answers: 1 / hits: 18357  / 8 Years ago, fri, december 9, 2016, 12:00:00

I have one problem! Where is the problem? e.keyCode is unknown. I using google chrome.





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);
}




More From » javascript

 Answers
4

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);
}




[#59761] Wednesday, December 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardob

Total Points: 571
Total Questions: 115
Total Answers: 96

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;