You console.log
is not working because it is initialized when the script load. What you need to do is to trigger your functions when the key is pressed.
// When the document is ready
$(function() {
$(document).keydown(function(e){
var key = e.which;
var a = 'a scoped variable';
switch (key) {
// Up arrow
case 38:
a = upArrowFunction(a); // Assign a to the returned value.
break;
// Down arrow
case 40:
downArrowFunction();
break;
}
});
function upArraowFunction(a) {
a = 'I change a, but a is not changed in keydown event';
return a; // But now I return the changed variable so it will change if a variable is assigned where the function is called.
}
function downArrowFunction() {
// Do something else
}
});