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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language.
Report a problem with this exampleOpens a pre-filled issue on GitHub.