Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
Listening for keydown / keypress events and differentiate between one and two digit numbers

I'm using an eventListener to detect numeric options in my vue app:

window.addEventListener("keydown", function (e) {
      switch (e.key) {
        case 1:
          // do stuff
          break;
        case 2:
          // do other stuff
      }
}

Since I have more than 9 options, I was wondering what the most sensible way would be to differentiate if the user is entering a one or two digit numer (e.g., 1 vs 11)?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Ended up adapting the solution described in this blog post, by pushing all keystrokes into an array, which is cleared if there is no input after 1 sec.

    let keys = [];
    let timeout = null;

    window.addEventListener("keydown", function (e) {
      
      keys.push(e.key);
      clearTimeout(timeout);
      timeout = setTimeout(function () {
          let input = parseInt(keys.join(""));
 
            switch (input) {
              case 1:
                // do stuff
                break;
              case 11:
                // do other stuff

          }          
          keys = [];  
      }, 1000);
    });
about 4 years ago · Juan Pablo Isaza Report

0

The switch statement is doing an implicit type conversion since e.key is a string, and the switch case specifiers are numbers. If you don't have more than 35 options, using base 36 digits ('1'-'9' and 'a'-'z') could be the easiest solution, in conjunction with constructing the switch statement along the lines of

  switch( e.key.toLowerCase() {
  case '1':  ... break;
  .
  .
  .
  case 'z':  ... break;
  }

I would hesitate before telling users they must hit a second digit within 500ms and wait that long before the first key they hit is recognized. :-)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!