ToggleEvent Typing For details Elements

The details toggle event arrives as a plain Event, so handlers cast to ToggleEvent once and read newState, oldState, and the open flag with full types.

TypescriptForm Validation

Code

typescriptsnippet
15 lines
declare const details: HTMLDetailsElement;

details.addEventListener('toggle', (event) => {
  // lib.dom 里 details 的 "toggle" 映射到 Event,需要一次窄化
  const t = event as ToggleEvent;
  console.log(`${t.oldState} -> ${t.newState}`, 'open flag:', details.open);
});

details.addEventListener('beforetoggle', (event) => {
  // beforetoggle 在状态翻转前触发,newState 是即将变成的状态
  const t = event as ToggleEvent;
  if (t.newState === 'open') {
    console.log('about to open, current:', details.open);
  }
});

Points of care

  • Exclusively built-in APIs, which leaves no supply chain worth auditing.

Using it

What you see on run is labeled — about to open, current: — when the file runs.

Output is labeled for readability — expect lines prefixed with about to open, current:.

Key statements

details.addEventListener('beforetoggle', (event) => {
  // beforetoggle 在状态翻转前触发,newState 是即将变成的状态
  const t = event as ToggleEvent;
  if (t.newState === 'open') {
    console.log('about to open, current:', details.open);
  }
});
details.addEventListener('toggle', (event) => {
  // lib.dom 里 details 的 "toggle" 映射到 Event,需要一次窄化
  const t = event as ToggleEvent;
  console.log(`${t.oldState} -> ${t.newState}`, 'open flag:', details.open);
});

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language.