Keyboard events and native controls
Quick answer
KeyboardEvent reports keyboard interaction. key describes the interpreted key, while code describes a physical key position when available. repeat reports autorepeat. Native buttons already provide keyboard activation and emit click; use a button for actions rather than recreating button behavior on a div. Use keydown for intentional custom keyboard navigation, and do not intercept typing or standard shortcuts unnecessarily.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const b=document.createElement("button");b.addEventListener("keydown",e=>console.log(e.key,e.code));b.dispatchEvent(new KeyboardEvent("keydown",{key:"a",code:"KeyQ"}));Expected console output:
a KeyQThe synthetic fixture deliberately supplies different interpreted and physical labels.
const b=document.createElement("button");let n=0;b.addEventListener("keydown",e=>{if(e.key==="Escape"&&!e.repeat)n++;});b.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape"}));b.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",repeat:true}));console.log(n);Expected console output:
1The handler ignores repeated keydown events.
Common mistake
Synthetic KeyboardEvent objects test handler logic, not the native default behavior of real keyboard input. Do not rely on deprecated keyCode.
Practice
Use Tab to reach a native button and Enter or Space to activate it. Compare the event log with a synthetic keyboard event.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Keyboard events and native controls — Knowledge Check
Apply the concept and predict the browser example behavior.
What does KeyboardEvent.key describe?
Why prefer a native button for an ordinary action?
Do synthetic keydown events establish real keyboard activation behavior?
What is the exact console output in Keyboard events and native controls example 1?
const b=document.createElement("button");b.addEventListener("keydown",e=>console.log(e.key,e.code));b.dispatchEvent(new KeyboardEvent("keydown",{key:"a",code:"KeyQ"}));What is the exact console output in Keyboard events and native controls example 2?
const b=document.createElement("button");let n=0;b.addEventListener("keydown",e=>{if(e.key==="Escape"&&!e.repeat)n++;});b.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape"}));b.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",repeat:true}));console.log(n);