How to programmatically dispatch a space press in JavaScript
2 July 2024 (Updated 18 May 2025)
// Create a keyboard event for the space key
const spaceEvent = new KeyboardEvent('keydown', {
key: ' ',
keyCode: 32,
code: 'Space',
which: 32,
bubbles: true,
cancelable: true
});
// Dispatch the event on the target element or document
document.dispatchEvent(spaceEvent);
Tagged:
JavaScript recipes