javascriptkeydownkeyuponkeydownonkeyup

How to detect combined keystroke (Alt + single-digit or multi-digit number) and get the number?


I'm trying to detect a combined keystroke consisting of Alt (held down) and a single-digit or multi-digit number and then retrieve the entered number for further processing. For example:

Input: Alt + 4 2

Desired output: 42

I guess I need to combine keydown and keyup together and store the entered digits in an array and then generate a number from them. How to achieve this?


Solution

  • You indeed shoulod take advantage of events keydown and keyup. We're using a global object to remember all the keys that are down, because they will fire different events.

    var obj_down = {}
    var digits = []
    
    window.addEventListener("keydown", function(ev) {
      obj_down[ev.key] = true;
      if (obj_down["Alt"] === true) {
        if (ev.key >= '0' && ev.key <= '9') {
          digits.push(+ev.key)
        }
      }
    })
    
    window.addEventListener("keyup", function(ev) {
      delete obj_down[ev.key];
      if (ev.key === 'Alt') {
        document.querySelector(".output").innerText = digits.join("")
        digits = []
      }
    })
    <p>hold alt and type a number</p>
    <input type="text">
    <br> output:
    <div class="output">