CSS and JavaScript UI State Patterns: Modals, Tabs, Menus, and Accessible Controls
JavaScriptCSSAccessibilityUI ComponentsFrontend DevelopmentDesign Systems

CSS and JavaScript UI State Patterns: Modals, Tabs, Menus, and Accessible Controls

CCode Compass Editorial Team
2026-11-12
9 min read

A practical checklist for building accessible JavaScript modals, tabs, accordions, menus, and disclosure controls with CSS and clear state management.

Reusable UI components are easier to maintain when their visual states, keyboard behavior, focus rules, and accessibility semantics are designed together. This guide provides a practical checklist for building modals, tabs, accordions, menus, and disclosure controls with CSS and JavaScript working in clearly defined roles.

Overview

An interactive component has at least two layers: a state model and a presentation model. The state model describes what is open, selected, expanded, or active. The presentation model controls how that state appears through CSS, HTML attributes, and visual styling. JavaScript should update the state and coordinate behavior; CSS should usually handle layout, visibility, transitions, and visual feedback.

Start with semantic HTML before adding custom behavior. A button is generally a better control for opening a panel than a styled div. A real link is appropriate for navigation. A native details and summary pair may be sufficient for simple disclosure content. Native elements provide useful keyboard and browser behavior, reducing the amount of JavaScript that must be tested.

Keep one source of truth for each component. For example, an accordion can use the button's aria-expanded value as the public state while a class or data attribute drives styling. Avoid situations where a hidden JavaScript variable, a CSS class, and an ARIA attribute can disagree. If the state changes, update every dependent representation in one function.

PatternTypical stateKeyboard behaviorPrimary accessibility considerations
Modal dialogOpen or closedEnter or Space opens a trigger; Escape usually closes the dialogDialog naming, initial focus, focus return, and background interaction
TabsOne selected tab and its associated panelArrow keys commonly move between tabs; Enter or Space may activate manually controlled tabsCorrect tab, tablist, and tabpanel relationships
AccordionEach panel expanded or collapsedButtons use normal button behavior; Enter or Space togglesExpanded state, controlled panel relationship, and visible focus
DisclosureOne trigger controls one revealed regionEnter or Space toggles the buttonClear labeling and synchronized expanded state
Menu or dropdownOpen or closed, sometimes with an active itemDepends on whether it is navigation, a listbox, or an application menuChoose semantics based on purpose rather than appearance

These patterns can be implemented with plain JavaScript, a framework component, or a design-system primitive. The framework does not remove the need to define behavior. React, Vue, Svelte, and other tools still need stable IDs, predictable state transitions, and deliberate focus management. For broader compatibility considerations, see the JavaScript Browser Compatibility Guide.

Checklist by scenario

  • Use a real button to open the dialog and give the dialog a visible heading.
  • Give the dialog an accessible name through a heading reference or an explicit label.
  • Move focus into the dialog when it opens, usually to the heading, first meaningful control, or a deliberately chosen close button.
  • Keep keyboard focus within the modal while it is active, unless the interaction is intentionally non-modal.
  • Allow Escape to close the dialog when that behavior is appropriate, and provide a visible close button as well.
  • Return focus to the element that opened the dialog after closing, provided that element still exists and is usable.
  • Prevent interaction with the page behind a modal. Use the platform's dialog behavior where suitable, or carefully manage background inertness and pointer events.
  • Do not use a modal for content that users need to compare with the underlying page. A disclosure, dedicated page, or non-modal dialog may be a better fit.

CSS can control the backdrop, positioning, opacity, and transition. JavaScript should control opening, closing, focus, and cleanup. If animation is used, respect the user's reduced-motion preference and ensure that hiding the dialog does not leave its controls in the tab order.

Tabs

  • Give the group a meaningful label when the surrounding context does not already identify it.
  • Associate each tab with exactly one panel using stable IDs and the appropriate relationships.
  • Expose which tab is selected and which panel is visible.
  • Choose an activation model deliberately. Automatic activation can feel responsive when panels are lightweight; manual activation can be preferable when switching triggers expensive work.
  • Define arrow-key behavior and make the selected tab reachable with normal keyboard navigation.
  • Support Home and End only if they are documented by the component's interaction model and implemented consistently.
  • Make the active and focused states visually distinct from inactive states.

Do not build tabs when the controls are actually navigation links or when the content would be clearer as a list of headings. Tabs are a relationship between a set of controls and panels, not simply a row of clickable labels.

Accordions and disclosure controls

  • Use a button for each trigger and keep the control's label understandable when read by itself.
  • Synchronize the expanded state with the visible panel.
  • Connect the trigger to the region it controls with a stable identifier.
  • Decide whether multiple panels may remain open. Do not make this behavior surprising or inconsistent across similar components.
  • Keep content in the document when it should be searchable, selectable, or available to assistive technology; visual collapse does not always require removing it from the DOM.
  • Use a native details element when its built-in behavior meets the design requirements.

An accordion should not be made keyboard-friendly by adding a click handler to a non-interactive element. Start with the correct HTML element, then enhance its appearance and behavior.

First identify what the control does. A navigation dropdown is usually a button or link that reveals navigation links. A listbox lets users choose a value. An application menu presents command-like actions with a distinct keyboard model. These patterns may look similar in CSS but are not interchangeable.

  • Use a button for a control that opens a panel without navigating.
  • Close the popup when the user completes an action or moves away according to the component's interaction model.
  • Support Escape and provide a predictable way to return focus to the trigger.
  • Make the popup placement and overflow behavior work at different viewport sizes.
  • Do not apply menu semantics merely because a component is visually styled as a dropdown.

For simple navigation, a disclosure pattern is often easier to understand and maintain than a fully managed application menu. Keep the JavaScript proportional to the interaction.

What to double-check

State and DOM synchronization

Write down the states before writing event handlers. For a modal, that may be closed and open. For tabs, define the selected tab, active panel, and focus position. For an accordion, decide whether each item is independent or whether opening one closes the others. Then identify the attributes, classes, and DOM properties that represent those states.

Test transitions in both directions. Open and close a dialog repeatedly, switch tabs in reverse order, expand every accordion item, and resize the viewport while a menu is open. Check that stale classes, duplicate IDs, and detached event listeners do not accumulate.

Focus and keyboard behavior

  • Begin with keyboard-only testing: Tab, Shift+Tab, Enter, Space, Escape, and arrow keys where relevant.
  • Confirm that the focus indicator remains visible against the component's background.
  • Check that hidden controls cannot receive focus.
  • Confirm that closing a component does not send focus to the page's top or to an unrelated element.
  • Test the component after validation errors, dynamic content updates, and asynchronous loading.

Focus management is often the difference between a component that looks accessible and one that is usable. Pair manual checks with automated testing, but do not treat an automated result as a complete accessibility review. The JavaScript Accessibility Testing Workflow provides a broader process for keyboard, focus, ARIA, and screen-reader checks.

Responsive and motion behavior

Use CSS for layout changes rather than adding separate JavaScript branches for every viewport width. A menu may change from an inline navigation pattern to a disclosure on a narrow screen, but the change should be explicit and tested at the breakpoint. Avoid relying on hover alone: touch devices and keyboard users need an equivalent action.

Transitions should not delay access to content or make a control appear unresponsive. Define what happens if a user activates a control again while an animation is running. Also test reduced-motion preferences and ensure that the component remains understandable with animation removed.

Integration and maintainability

Give reusable components a small, documented API. Define which element owns state, which events are emitted, how IDs are generated, and what happens when content is removed. In a framework, preserve stable keys and avoid generating different IDs during server and client rendering. In plain JavaScript, use event delegation carefully and clean up listeners when components are destroyed.

Include interaction tests in the same workflow as unit and visual tests. Review the component's HTML output, not only its appearance. The JavaScript Testing Guide can help place keyboard and interaction checks alongside broader test coverage.

Common mistakes

  • Using ARIA to repair incorrect HTML. ARIA can communicate relationships and states, but it does not turn a generic element into a fully functioning button or dialog. Use semantic elements first.
  • Managing visibility with CSS alone. A visually hidden or transparent element may still be reachable or announced if its interactive state is not managed correctly.
  • Leaving focus behind a modal. Users may continue tabbing through page content while believing they are inside the dialog.
  • Returning focus to a removed trigger. Dynamic interfaces can destroy the original opener. Define a fallback target before closing.
  • Confusing dropdowns with menus. A navigation disclosure, a listbox, and an application menu have different purposes and interaction expectations.
  • Making click handlers do everything. Mouse events do not automatically cover keyboard activation, focus changes, touch input, or screen-reader interaction.
  • Relying on color alone. Selected, expanded, focused, and disabled states should have more than a subtle color change when the design requires users to distinguish them.
  • Duplicating component logic. Separate implementations of the same modal or accordion often drift apart. Centralize behavior or use a reviewed design-system primitive.
  • Testing only the happy path. Test repeated activation, rapid input, browser back navigation, viewport changes, failed network requests, and content that is longer than the original design.

When adding a third-party component library, inspect its generated markup, focus behavior, update cadence, and customization model before adopting it. A package can save implementation time while still requiring project-specific accessibility and browser testing. See How to Evaluate npm Packages Before Adding Them to a JavaScript Project for a wider evaluation checklist.

When to revisit

Revisit an interactive component whenever its content, design, browser support target, or implementation approach changes. A seasonal planning cycle is a useful prompt for checking shared components before a high-traffic campaign or major content refresh. Also review the component when a design system changes its spacing, motion, breakpoint, color, or typography tokens.

Use this practical review sequence:

  1. Open the component with a keyboard and identify every reachable control.
  2. Record the expected states and compare them with the DOM attributes and CSS classes.
  3. Check the accessible name, role, value, and relationship for each control and panel.
  4. Test focus before opening, while open, after switching state, and after closing.
  5. Repeat the test at narrow and wide viewport sizes, with reduced motion enabled, and with content longer than the design mockup.
  6. Run automated checks, then complete a manual screen-reader or assistive-technology pass appropriate to the product.
  7. Document any intentional behavior, such as manual tab activation or multiple accordion panels remaining open.

When browser behavior or framework conventions change, verify the component rather than assuming that old workarounds are still needed. Keep the implementation small, preserve semantic HTML, and update tests with every behavior change. For code quality, security, performance, and maintainability checks around the implementation, use the JavaScript Code Review Checklist.

The most reliable JavaScript UI patterns are not the ones with the most code. They are the ones whose state is easy to explain, whose keyboard behavior is predictable, whose focus is intentionally managed, and whose CSS and JavaScript responsibilities remain clear.

Related Topics

#JavaScript#CSS#Accessibility#UI Components#Frontend Development#Design Systems
C

Code Compass Editorial Team

Frontend Development Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.