0

I'm trying to write a web based app in JavaScript and I came across a little a little hurdle when trying to write a piece of code that returns either true or false depending on what key the user pressed.

Here is the code:

function getKey(key)
{
 window.addEventListener("keydown", function(e) {
  return e.keyCode === key;
 });
}

This always returns 'undefined', and I can't get it to work. I would greatly appreciate if someone answered and fixed my little problem.

Thanks!

  • 1
    Notice, that the returned value from a click listener goes to the bit space. You're probably waiting a return value from `getKey`, but it's not returning anything. Please show also the code which calls `getKey`, and how you're going to use the return value. – Teemu Sep 05 '16 at 15:46
  • 1
    The event(s) occur after your function returns. There's no way to wait for them. – Bergi Sep 05 '16 at 15:47
  • Trigger whatever you want to do on a keypress *inside* the event listener itself. – Phylogenesis Sep 05 '16 at 15:48

0 Answers0