element.animate Runs Typed Keyframes

element.animate drives keyframes from script — a horizontal shake on failed validation — with a finished promise that resolves when the run ends.

TypescriptForm Validation

Code

typescriptsnippet
19 lines
const field = document.querySelector<HTMLElement>('#email-field');

if (field) {
  // 校验失败时横向抖动:WAAPI 直接驱动关键帧,不需要 CSS keyframes 规则
  const shake = field.animate(
    [
      { transform: 'translateX(0px)' },
      { transform: 'translateX(-6px)' },
      { transform: 'translateX(6px)' },
      { transform: 'translateX(0px)' },
    ],
    { duration: 200, iterations: 2 },
  );

  // finished 是 Promise:动画结束或取消时落定
  shake.finished
    .then(() => console.log('shake done, focus field'))
    .catch(() => console.log('shake cancelled'));
}

What the code does

The snippet works against one binding, field, grabbed by document.querySelector at top level.

Watch out for

  • document comes from the browser’s DOM, so run this where a DOM exists — a bare Node process has nothing to query.

Applying it

Running the file prints labeled results such as shake done, focus field, shake cancelled — which of the two appears tells you whether shake.finished resolved or was cancelled.

Statements that matter

const field = document.querySelector<HTMLElement>('#email-field');
shake.finished
.then(() => console.log('shake done, focus field'))
.catch(() => console.log('shake cancelled'));

Interactive Tools for This Topic

FAQ

Does element.animate Runs Typed Keyframes 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.