The Tab key is used by browsers for keyboard focus navigation. JavaScript can detect a Tab key press with KeyboardEvent.key === "Tab" or the older keyCode === 9. However, JavaScript cannot reliably force the browser to perform native Tab navigation by dispatching a fake keyboard event.
Use JavaScript to detect Tab, respond to focus changes, or move focus intentionally with .focus(). Do not depend on simulated Tab key events for real accessibility behavior.
Tested On: Keyboard helper examples were tested with Node.js v20.18.1 on a Linux system. Actual Tab focus movement and keyboard events must be tested in a browser because focus handling is browser-controlled.
Method 1: Detect Tab with KeyboardEvent.key
document.addEventListener("keydown", (event) => {
if (event.key === "Tab") {
console.log("Tab pressed");
}
});Helper test:
function isTab(event) {
return event.key === "Tab" || event.keyCode === 9;
}
console.log("tab-key:", isTab({ key: "Tab" }));Tested output:
tab-key: trueMethod 2: Understand Tab keyCode 9
console.log("tab-keycode:", isTab({ keyCode: 9 }));Tested output:
tab-keycode: truekeyCode is legacy. Prefer event.key, but knowing that the Tab key code is 9 helps when maintaining old code.
Method 3: Move Focus Instead of Simulating Tab
If the goal is to move to another field, call .focus() on the target element.
const next = document.querySelector("#email");
next?.focus();This is more reliable than trying to dispatch a fake Tab key event.
Method 4: Prevent Default Tab Behavior Carefully
document.addEventListener("keydown", (event) => {
if (event.key === "Tab") {
event.preventDefault();
document.querySelector("#next-field")?.focus();
}
});Avoid trapping keyboard users unless you are implementing a proper modal dialog or focus-managed widget.
Common Questions About JavaScript Tab Key
What is the keyCode for Tab?
The legacy keyCode for the Tab key is 9.
Can JavaScript send a real Tab key press?
JavaScript can dispatch a KeyboardEvent, but browsers generally do not treat synthetic events as trusted native keyboard input for focus navigation.
What should I use instead of simulating Tab?
Use .focus() to move focus to a specific element, and use proper HTML focus order for normal keyboard navigation.
Summary
Use event.key === "Tab" to detect the Tab key in JavaScript and remember that legacy code may use keyCode 9. For moving focus, call .focus() on the target element rather than trying to simulate a real Tab key press. Browser focus behavior should always be tested with an actual keyboard.
