How to detect Backspace
document.addEventListener('keydown', (event) => {
if (event.key === "Backspace") {
// Backspace 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 Backspace
Backspace deletes the character before the caret. Old browsers used it for “Back”; current ones don’t. To detect edits, prefer the beforeinput event with inputType: "deleteContentBackward".
In React
<input onKeyDown={(e) => { if (e.key === "Backspace") { /* … */ } }} />