How to detect Tab
document.addEventListener('keydown', (event) => {
if (event.key === "Tab") {
// Tab 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 Tab
Tab moves focus to the next focusable element and Shift+Tab to the previous one. Only capture it in widgets that need it, such as code editors — and give keyboard users a way out (for example Escape, then Tab).
In React
<input onKeyDown={(e) => { if (e.key === "Tab") { /* … */ } }} />