How to detect Space
document.addEventListener('keydown', (event) => {
if (event.key === " ") {
// Space was pressed
}
});
Use event.key to react to what the key means (it follows the keyboard layout) and event.code for its physical position, for example WASD in games. keyCode and which are deprecated: they still work, but their values differ between browsers and layouts.
How browsers treat Space
The key value is a single space character, not “Space”. Space activates buttons and checkboxes and scrolls the page when nothing else handles it; call preventDefault() if your custom control uses it, or the page will jump.
In React
<input onKeyDown={(e) => { if (e.key === " ") { /* … */ } }} />