Passing Parameters To Keydown
Solution 1:
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 arrowcase38:
a = upArrowFunction(a); // Assign a to the returned value.break;
// Down arrowcase40:
downArrowFunction();
break;
}
});
functionupArraowFunction(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.
}
functiondownArrowFunction() {
// Do something else
}
});
Solution 2:
Do did you mean to have the console.log inside the keydown
function?
I was able to get it to respond (as I would expect) like this:
$(function() { /* on page load load */var a = 38;
var b = 0;
$(document).bind('keydown',function(e){
var key = e.which;
if (a === key) {
b=key;
}
console.log(a, b, key);
});
});
within the scope of the keydown function, a and b get set properly if you hit the up-arrow.
I suspect that what was happening was that your console.log happened on page load. Then after that, you initialized the binding and so you never saw the updated results.
Solution 3:
Try this
$(document).on("keydown", function(e, key){
var a = 38;
var b = 0;
if (e.which === a) {b = e.which};
var key = (key === undefined ? b : a);
returnconsole.log(a + " " + b + " " + key)
});
Edit
yes but the problem is that within key down I can't use a and b because they get set to undefined and I have to initiate them in another part of my program – user3030188
Call your functions when the keydown event is triggered and maybe you could send the variable to the function instead of making it global. – L105
Yah that makes sense but what im wondering is whether I could pass in a or b as a case statement if I defined them in another part of the program would they get overridden why would it return undefined? – user3030188
Try this
functionkey(e, a, b, key) {
/* settings */var a = (a === undefined ? 38 : a);
var b = (b === undefined ? 0 : b);
if (e.which === a) {b = e.which};
var key = (key === undefined ? b : a);
returnconsole.log(a + " " + b + " " + key)
};
$(document).on("keydown", key); /* `38` `38` `38` *//* `a`, `b` */
$(document).on("keydown", key({},undefined,undefined,undefined)); /* `38` `0` `0` *//* a`, `b`, or `n` */
$(document).on("keydown", function(n) {
var n = 35;
key({},37,n,undefined)
}); /* `37` `35` `35`*//* `n` */
$(document).on("keydown", function(n) {
var n = 35;
key({},n,n,undefined)
}); /* `35` `35` `35`*/
Post a Comment for "Passing Parameters To Keydown"