title: Simulate keypress event (in plain js)
body: <p>I'm looking for an example of <strong>how to simulate a keypress event</strong> in js.</p>
  
  <p>The examples I've found all use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/initEvent" rel="nofollow noreferrer">the deprecated Event.initEvent method</a>. </p>
  
  <p>When I try using <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent" rel="nofollow noreferrer">the recommended KeyboardEvent</a> instead, it doesn't work - the input is not updated.</p>
  
  <pre><code>&lt;input id="myInput" /&gt;
  
  const element = document.getElementById('myInput')
  const keypressEvent = new KeyboardEvent('keypress', {
    code: 'KeyA'
  })
  element.dispatchEvent(keypressEvent)
  </code></pre>
  
  <p>What is wrong or missing in the above code? Does the element need to take focus first or something like that?</p>