Choose keys by meaning and layout
Use KeyboardEvent.key when the action should follow the character produced by the user’s layout, and KeyboardEvent.code when a physical position matters more. This distinction affects different keyboard layouts. Offer a consistent mapping and show it in the instructions instead of assuming everyone expects WASD.
Avoid hijacking keys while a text field or editable control has focus. Prevent browser defaults such as page scrolling only when the game surface actively handles that key. This keeps the game from swallowing ordinary typing or disrupting browser navigation before the player enters the interactive area.
Track held state and release
For continuous movement, set a key’s held state on keydown and clear it on keyup. Browsers can repeat keydown while a key remains held, so a one-shot action such as jumping should ignore repeats unless repeated activation is part of the design. Clear held keys when the game loses focus or the window blurs, since keyup may arrive after focus has moved elsewhere.
Test two keys together, a long hold, a quick tap and focus leaving then returning. Ignore repeated keydown for one-shot actions unless repetition is intended. MDN documents KeyboardEvent.key, code and event types; choose the property that matches your mapping.
Questions about keyboard controls for browser games
Should I use key or code for a game control?
Use key when the character value or keyboard layout should determine the action. Use code when the physical key position is the intended control. Make the choice explicit and test alternate layouts.
Why clear held keys when the page loses focus?
The browser may not deliver the release event to the game after focus changes. Clearing input state prevents movement from remaining active when the player returns.