admin管理员组

文章数量:1291041

I want my code to console.log when I press number pad 1 I tried this, but is not working:

function presskey1(e){
    if(e.keyCode == 97){
        console.log(Element)
    }
}
presskey1();

I want my code to console.log when I press number pad 1 I tried this, but is not working:

function presskey1(e){
    if(e.keyCode == 97){
        console.log(Element)
    }
}
presskey1();

97 = numpad 1 codeKey

Share Improve this question edited Oct 6, 2020 at 20:11 Arian Acosta 6,8271 gold badge37 silver badges32 bronze badges asked Oct 6, 2020 at 20:07 ExtraordinaryExtraordinary 862 silver badges12 bronze badges 5
  • There's a number of missing parts here. Can you provide a working example? – Pipetus Commented Oct 6, 2020 at 20:10
  • thats why im asking , im not sure how this even works – Extraordinary Commented Oct 6, 2020 at 20:11
  • 1 In the example you're not passing e to the function; you're passing empty arguments, which turn e into undefined – Pipetus Commented Oct 6, 2020 at 20:11
  • Does this answer your question? Detecting arrow key presses in JavaScript – HoldOffHunger Commented Oct 6, 2020 at 20:12
  • No, so I want it to console.log when I press number 1 on the keyboard. – Extraordinary Commented Oct 6, 2020 at 20:15
Add a ment  | 

3 Answers 3

Reset to default 5

Here's how you can do it! You should use event listener for keydown event and also key code for numpad 1 is Numpad1

document.addEventListener('keydown', keyPressed);

function keyPressed(e) {
  if(e.code == "Numpad1") {
    console.log("Numpad1 Pressed");
  }
}

// this works for me.
// it logs relevant keycode info.


  const keyCodes = () => {
  document.addEventListener('keydown', function (e) {
    console.log(
      'keyCodeDEP', e.which,
      'key', e.key,
      'code', e.code,
      'location', e.location
    );
  });
};
keyCodes();

https://keycode.info/

document.addEventListener('keydown', (event) => {
  if (event.key === "1"){
     console.log(event.target) 
  }
})

本文标签: javascriptHow to consolelog when I press a key in the keyboardStack Overflow