input Streams Keystrokes, change Commits

input fires on every value mutation while change waits for a commit; dispatching both shows which handler updates UI live versus on blur.

JavascriptForm Validation

Code

javascriptsnippet
19 lines
if (typeof document === 'undefined') {
  console.log('DOM unavailable in this runtime');
} else {
  const log = [];
  const input = document.createElement('input');

  // input 每次值变化都触发;change 只在提交(失焦/回车)后触发
  input.addEventListener('input', () => log.push('input:' + input.value));
  input.addEventListener('change', () => log.push('change:' + input.value));

  // 模拟两次键入 + 一次失焦提交
  input.value = 'ab';
  input.dispatchEvent(new Event('input', { bubbles: true }));
  input.value = 'abc';
  input.dispatchEvent(new Event('input', { bubbles: true }));
  input.dispatchEvent(new Event('change', { bubbles: true }));

  console.log(log.join(' | '));
}

What to watch for

  • No package installation, no environment variables, no setup steps.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

A browser run prints one merged line — input:ab | input:abc | change:abc — while Node stops at the DOM unavailable in this runtime fallback.

The statements worth quoting

input.addEventListener('change', () => log.push('change:' + input.value));
input.addEventListener('input', () => log.push('input:' + input.value));

Interactive Tools for This Topic

FAQ

Does input Streams Keystrokes, change Commits 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.