-1

I'm trying to create a program that can detect that the V key has been pressed on the keyboard, and when it detects that it has been pressed, it would declare a variable as being true. This variable being true would mean that when the SHIFT key is pressed, it would also press keypad one at the same time. And once the V key has been pressed again, it would declare the variable as being false and pressing the SHIFT key would not press keypad one.

  • does this answer your question https://stackoverflow.com/questions/4416505/how-to-take-keyboard-input-in-javascript – kimcodes Oct 03 '20 at 22:10
  • I've tried doing something similar before, and I get the error: ReferenceError: document is not defined – dindotjs Oct 03 '20 at 22:14
  • Hi! Questions seeking code help must include the shortest code necessary to reproduce it in the question itself preferably in a Stack Snippet. Please, read the [How to ask](https://stackoverflow.com/help/how-to-ask) section to improve your question – Inazense Oct 03 '20 at 22:49

1 Answers1

0

You can use the keydown event listener to detect when the "V" or "Shift" keys are pressed. Try this:

document.body.addEventListener("keydown",function(e){
    e = e || window.event;
    var key = e.which || e.keyCode; // keyCode detection
    var shift = e.shiftKey;

    
    if ( key == 86) {
        alert("V Pressed !");
    } else if (shift) {
        alert("Shift Pressed!");
    }
},false);

Modified from this answer: how to detect CTRL+C and CTRL+V key pressing using regular expression?

dwosk
  • 1,122
  • 7
  • 10
  • I've tried doing similar things, and I have persistently gotten the error: document.body.addEventListener("keydown",function(e){ ^ ReferenceError: document is not defined I'm probably doing something very silly here, but I'm just not sure what. – dindotjs Oct 03 '20 at 21:56
  • I'm assuming you're running the code in a browser? Also, I'm not following what you want to do with "keypad one" but the code above should be a good starting point. – dwosk Oct 03 '20 at 22:00
  • I'm using the Visual Studio Code application to run the code, so will that be the problem? – dindotjs Oct 03 '20 at 22:04