Search code examples
javascriptaddeventlistenerkeypress

I can't console.log the key that I pressed with addEventListener in my squaring calculator using JavaScript?


It's not giving errors. I just did the code normally and it didn't work, then I used a function, and then I used a window.onload, and then I used a while loop, and it's still not working. The code looks like this:

JavaScript code:

function square() {
  function foo(n) {
    return n * n;
  }
  window.addEventListener('keypressed', checkKeyPress, false);

  function checkKeyPress(key) {
    if (key.code == '48' || key.code == '49' || key.code == '50' || key.code == '51' || key.code == '52' || key.code == '53' || key.code == '54' || key.code == '55' || key.code == '56' || key.code == '57') {
      console.log(foo(key));
    }
  }
  checkKeyPress('566');
}
window.onload = square();

Also, it isn't giving errors, it's just not working. This is from a while ago and I think there was something wrong with the tutorial I watched that while ago.


Solution

  • Firstly it's not a good practice to declare a function and event listeners inside the function. Secondly, in the example which you provided, console.log() don't call, because if statement returns false. Thirdly, keypressed is not a valid event. There are keypress, keyup, keydown.