2

I've tried so many things but still I can't figure it out how to Press the Q Keydown event? My Code is this

JavaScript

document.addEventListener('keydown', function(e) {
  if (e.key === 'q')
    e.keypress = '1';
})
<div id="weapon_ui_container" style="display: block;">
  <div class="weapon_button round_border hovered" id="weapon_ui_button_1" onclick="UI.weaponsUIController.onUIWeaponClick(0)">
    <img src="/assets/sprites/entities/weapons_ui/hands_ui.png" class="weapon_button_image" id="weapon_button_image_1"> 1 </div>
  <div class="weapon_button round_border" id="weapon_ui_button_2" onclick="UI.weaponsUIController.onUIWeaponClick(1)">
    <img src="/assets/sprites/entities/weapons/hands.png" class="weapon_button_image" id="weapon_button_image_2"> 2 </div>

I need some help I'm new to js.

Rajesh
  • 24,354
  • 5
  • 48
  • 79
PSK1337
  • 41
  • 1
  • 7

1 Answers1

1

If you want to enable keypress of letter Q or q, then this code can help you:

document.addEventListener('keydown', function(e) {
  if (e.keyCode == 113 || e.keyCode == 81){
    e.keypress = '1';
    alert("pressed");
  }
});

In your code, you have missed a { after the if condition. And its always better to access the key by there key codes because they are unique and there is no ambiguity.

Here is a link to check what are the keycodes of all the key presses that you might want to use.

Code_Ninja
  • 1,729
  • 1
  • 14
  • 38
  • `keyCode` is deprecated, and the usage in combination with the `keydown` event is a bad idea. Using the key code can additional lead to other problems if you have different keyboard layouts, because the code represents the physical key before the keyboard layout it applied. – t.niese Sep 14 '18 at 06:20
  • @t.niese If there is any better idea here, i will appreciate it, because I used `keyCode` a long time ago, and haven't updated my knowledge on `keyCode` since then. I used this in answer because this code was a working example of what he might wanna do, it will be really nice if someone answers another updated version of this code. – Code_Ninja Sep 14 '18 at 06:29