Keyboard Events Separate key From code

event.key is the layout-interpreted character while event.code is the physical key, so shortcuts survive keyboard layouts and IME composition states.

JavascriptForm Validation

Code

javascriptsnippet
25 lines
// event.key is the character after layout/IME interpretation, while event.code is the physical key (named for its US-layout position):
// shortcut matching uses code to stay layout-independent; semantic checks like Enter-to-submit use key and exclude IME composition
const input = document.createElement('input');
document.body.append(input);
const actions = [];

input.addEventListener('keydown', (event) => {
  if (event.ctrlKey && event.code === 'KeyS') actions.push('save');
  else if (event.key === 'Escape') actions.push('close');
  else if (event.key === 'Enter') {
    // Enter during IME composition confirms the candidate instead of submitting
    actions.push(event.isComposing ? 'ignore-ime' : 'submit');
  } else actions.push('none');
});

// on AZERTY the physical key labelled Q (code 'KeyA') produces the character 'q' — key follows the layout, code does not
const presses = [
  new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter' }),
  new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', isComposing: true }),
  new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape' }),
  new KeyboardEvent('keydown', { key: 's', code: 'KeyS', ctrlKey: true }),
  new KeyboardEvent('keydown', { key: 'q', code: 'KeyA', ctrlKey: true }),
];
for (const press of presses) input.dispatchEvent(press);
console.log('actions:', actions.join(','));

The runtime story

Repetition is confined to for (const press of presses) input.dispatchEvent(press); — the rest of the file is straight-line.

Top-level bindings input, actions, presses hold the demo state — nothing sits inside a function scope.

Watch out for

  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Putting it to use

The demo output is labeled (actions:); each label names the call that printed it.

Interactive Tools for This Topic

FAQ

Does Keyboard Events Separate key From code run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.