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

193
Views
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 answers
Answer question

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 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!