Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda