Expand/Collapse Widget Demonstration

These widgets use the native <details> element for accessible expand/collapse behavior, enhanced with custom styling and scripted behaviors.

1. Basic Expand/Collapse

How does the basic widget work?

The simplest widget relies on the native HTML summary element to toggle the visibility of its associated content. This means keyboard support and screen reader announcements all work automatically.

  • Click or press Enter on the summary to toggle the panel.
  • The content below the summary becomes visible when the widget is expanded.
  • Pressing Shift + Tab returns focus to earlier interactive elements.

2. Default-Open Panel with Rich Content

What makes this section stay open?

Setting the open attribute keeps a <details> element expanded until the user decides to close it. This is useful for highlighting information that should be visible on first load.

  1. Pre-expanded: The open attribute signals initial visibility.
  2. Auto status badge: The label on the right is injected via a data-status attribute.
  3. Rich formatting: Lists, code samples, and other semantic HTML can live in the controlled panel.
Stacked books on a desk
Figure: Panels can hold media, such as images or charts.

3. Accordion Mode (Mutually Exclusive)

Why would I use an accordion?

When space is limited, an accordion ensures that only one panel is open at a time. This keeps focus on the active topic while collapsing the others for you.

How is exclusivity enforced?

A tiny script listens for the toggle event on each panel. When one opens, the script closes its siblings within the same data-accordion container.

This approach still respects native semantics—keyboard users and assistive technologies receive the same cues as they would with standalone expanders.

Can I add transitions?

Yes. Although the <details> element does not animate height out-of-the-box, you can use CSS transitions on child wrappers or employ the Web Animations API to orchestrate smooth expansion.

Always ensure that animations are subtle and respect the user’s prefers-reduced-motion preference.

4. Programmatic Control and Status Sync

Can scripts manipulate the open state?

Absolutely. This panel demonstrates synchronizing UI state with a script. The button above toggles every widget on the page to the opposite state and updates status badges as needed.

How is the badge updated?

The script observes each toggle event. When a panel opens, it sets a data-status attribute on the <details> element, allowing CSS to render the label automatically.