Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
Programmatically dispatch keyboard (e.g. keypress) events using JavaScript

I am trying to dispatch events programatically for keyboard and mouse events.

So far there are few things I have tried. Right now I am able to dispatch mouse events programatically and see the changes:

const element = document.getElementById("element");
const event = new Event('click', {bubbles: true});
element.dispatchEvent(event);

Above method is working fine for Mouse Event. And I have tried following method for keyboard events:

const element = document.getElementById("input-element");
const event = new KeyboardEvent('keypress', {'key': 'e'});
element.dispatchEvent(event);

It seems here that the event is being executed, but the values are not being updated in the input field.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are a number of events that occur when you press a key. None of them result in an input value being changed, but you can use this function to approximate what happens when a key is pressed.

const element = document.getElementById("input-element");
const key = 'e';

var success = triggerKey(key, element);
console.log(success?'success':'fail');

function triggerKey(key, element){
  if(!/^[a-z]$/.test(key)) return false;
  if(!['INPUT','TEXTAREA'].includes(element.tagName)) return false;
  const events = ['keydown', 'keypress', 'textInput', 'keyup'];
  events.forEach(event_name=>{
    const opts = 'textInput' === event_name ? {
      inputType: 'insertText',
      data: key
    } : {
      key: key,
      code: `Key${key.toUpperCase()}`
    };
    const event = 'textInput' === event_name ? 
      new InputEvent('input', opts) :
      new KeyboardEvent(event_name, opts);
    element.dispatchEvent(event);
    if('textInput' === event_name) element.value += key;
  });
  return true;
}
<input id="input-element">

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda