Dispatching Events

Construct a built-in event and fire it with target.dispatchEvent(event). Listeners run synchronously, and the call returns false if the event is cancelable and a listener called preventDefault(). Constructor flags default to false, so pass bubbles: true when ancestors must hear the event.

Dispatching synthetic keydown eventsHTMLLive
<input value="abc"> <output></output>
<script>
  const [input, out] = document.querySelectorAll("input, output");
  input.addEventListener("keydown", (e) => { if (e.key === "x") e.preventDefault(); });
  for (const key of ["e", "x"]) {
    const ok = input.dispatchEvent(new KeyboardEvent("keydown", { key, cancelable: true }));
    out.append(`${key}: ${ok}; `);
  }
</script>
Browser output of Listing 8.51
Browser output of 51

Synthetic events mostly skip default actions: in Chrome 1 a dispatched click still toggles a checkbox, but the keydown above typed nothing. For real input in tests, drive the browser with Playwright 26,280 .