# GENERAL: [Books](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/general/books) A curated list of essential UX books to help developers improve their design and implementation skills. # UX Books for Developers A curated list of books to help developers understand and implement better user experiences. ## Essential Reads | Cover | Title | Author | Why Developers Should Read It | | ------------------------------------------------------------------------------------ | ------------------------------------------------ | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | ![Don't Make Me Think](https://covers.openlibrary.org/b/isbn/0321965515-M.jpg) | Don't Make Me Think, Revisited | Steve Krug | • Practical usability principles
• Developer-friendly approach
• Real-world examples | | ![UX Fundamentals](/books/ux-fundamentals-non-ux-professionals.jpg) | UX Fundamentals for Non-UX Professionals | Edward Stull | • Perfect for developers new to UX
• Clear, structured approach
• Focuses on core concepts | | ![Design of Everyday Things](https://covers.openlibrary.org/b/isbn/0465050654-M.jpg) | The Design of Everyday Things | Don Norman | • Fundamental design principles
• Understanding user psychology
• Error prevention | | ![Practical UI](/books/practical-ui.jpg) | [Practical UI](https://www.practical-ui.com/) | Adham Dannaway | • Logic-driven approach
• Quick, actionable guidelines
• Includes Figma design system
• Updated in 2024 | | ![Refactoring UI](/books/refactoring-ui.jpg) | [Refactoring UI](https://www.refactoringui.com/) | Adam Wathan & Steve Schoger | • Design tactics for developers
• Practical, visual examples
• Component-based approach
• Color & typography guidelines | ## Form Design | Cover | Title | Author | Why Developers Should Read It | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | ![Designing UX: Forms](/books/designing-ux-forms.jpg) | Designing UX: Forms | Jessica Enders | • Deep dive into form design psychology
• Best practices for validation
• Accessibility considerations
• Mobile-first approach | | ![Form Design Patterns](/books/form-design-patterns.jpg) | Form Design Patterns | Adam Silver | • Step-by-step implementation guide
• Progressive enhancement techniques
• Accessibility best practices
• Real-world examples | | ![Dos and Don'ts for Form Input](/books/do-dont-forms.jpg) | [Dos and Don'ts for Form Input and Selection](https://uxmovement.gumroad.com/l/dodontform) | UX Movement | • Comprehensive form patterns
• Visual examples
• Practical dos and don'ts
• Regular updates included | ## Tools & References | Cover | Title | Author | Why Developers Should Read It | | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | ![Smart Interface Design Patterns](/books/smart-interface-design-patterns.jpg) | [Smart Interface Design Patterns Checklist Cards](https://www.smashingmagazine.com/2020/08/checklist-cards-release/) | Vitaly Friedman | • 100 ready-to-use checklists
• Covers all common UI components
• Based on usability research
• Perfect for design-implementation discussions | ## Inclusive Design | Cover | Title | Author | Why Developers Should Read It | | ------------------------------------------------------------------ | ------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | ![Inclusive Design Patterns](/books/inclusive-design-patterns.jpg) | Inclusive Design Patterns | Heydon Pickering | • Practical accessibility techniques
• ARIA implementation patterns
• Progressive enhancement strategies
• Cross-browser solutions | ## Advanced UX | Cover | Title | Author | Why Developers Should Read It | | --------------------------------------------------------------------- | ---------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------- | | ![About Face](https://covers.openlibrary.org/b/isbn/1118766571-M.jpg) | About Face: The Essentials of Interaction Design | Alan Cooper | • Interaction design patterns
• User behavior models
• Interface guidelines | | ![100 Things](https://covers.openlibrary.org/b/isbn/0321767535-M.jpg) | 100 Things Every Designer Needs to Know About People | Susan Weinschenk | • Psychology insights
• Research-based decisions
• Practical applications | # GENERAL: [Getting Started](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/general/getting-started) UX Patterns for Devs is a comprehensive resource that helps developers implement effective, accessible, and usable UI components # Getting Started ## About UX Patterns for Devs UX Patterns for Devs is a comprehensive resource that helps developers implement effective, accessible, and usable UI components. Each pattern in our documentation is carefully crafted to provide practical guidance while following best practices for user experience and accessibility. ## How to Use This Documentation Each pattern in our documentation follows a consistent structure to help you quickly find the information you need: 1. **Overview** - Introduction and use cases for the pattern 2. **Use Cases** - Real-world examples and scenarios where the pattern should be implemented 3. **Benefits** - Key advantages and value propositions of using this pattern 4. **Anatomy** - Detailed breakdown of the component's structure 5. **Best Practices** - Guidelines for implementation, including do's and don'ts 6. **Micro-Interactions & Animations** - Detailed guidance on animations, transitions, and interactive feedback 7. **Tracking & Analytics** - Event tracking implementation and metrics analysis 8. **Localization** - Guidelines for translating and adapting the pattern 9. **Code Examples** - Code examples and technical considerations 10. **Accessibility** - Guidelines for accessibility considerations 11. **SEO** - Search engine optimization considerations and best practices 12. **Browser Support** - Information on browser support for the pattern 13. **Testing** - Guidelines for unit, integration, and accessibility testing 14. **Design Tokens** - Design system variables and customization options 15. **Related Patterns** - Links to similar or complementary patterns 16. **FAQs** - Common questions and detailed answers 17. **Resources** - Additional documentation, articles, libraries... ## Getting Started To get the most out of this documentation: 1. **Browse Patterns** - Use the sidebar navigation to explore available patterns 2. **Search** - Use the search bar to find specific patterns or concepts 3. **Implementation** - Follow the code examples and guidelines for each pattern 4. **Accessibility** - Pay attention to accessibility requirements for each component 5. **Best Practices** - Review the do's and don'ts before implementing ## How Would We Define "Build Effort"? Each pattern has a complexity indicator using this simple scale: | Level | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------- | | 🟢 Low | Simple implementation, minimal dependencies, little to no JavaScript required (e.g., Tooltip, Expandable Text). | | 🟡 Medium | Requires state management, user interactions, and accessibility considerations (e.g., Load More, Modal). | | 🔴 High | Complex UI behavior, animations, accessibility, performance optimizations, and multiple edge cases (e.g., Carousel, Infinite Scroll). | ## Contributing We welcome contributions from the community! Whether you want to: * Add new patterns * Improve existing documentation * Fix bugs * Suggest improvements Visit our [GitHub repository](https://github.com/thedaviddias/ux-patterns-for-developers/blob/main/.github/CONTRIBUTING.md) to learn how to contribute. ## Need Help? If you need assistance or want to report an issue: * Open a [GitHub issue](https://github.com/thedaviddias/ux-patterns-for-developers/issues/new/choose) * Join our [Discord community](https://ddias.link/discord) * Check the pattern's documentation for specific implementation details # GENERAL: [When To Use What](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/general/when-to-use-what) Guide for choosing the right UI pattern for your needs # When to Use What? This guide helps you choose the most appropriate UI pattern for your needs. Each pattern includes: * ✅ Best use cases * ❌ When to avoid * 🎯 Key features * 🔄 Related patterns ## Selection Patterns (Less than 5 options) | Pattern | Best For | Avoid When | Key Features | Related | | ------------------------------------ | -------------------------------------------- | ------------------------------------ | --------------- | -------------------------------------------------- | | [Radio](/patterns/forms/radio) | ✅ Single choice
✅ Visible options | ❌ Many options
❌ Multiple needed | ✅ Clear choices | [Dropdown](/patterns/forms/selection-input) | | [Checkbox](/patterns/forms/checkbox) | ✅ Multiple choices
✅ Independent options | ❌ Single choice
❌ Many options | ✅ Toggle states | [Multi-select](/patterns/forms/multi-select-input) | | [Toggle](/patterns/forms/toggle) | ✅ Binary settings
✅ Immediate effect | ❌ Multiple states | ✅ Quick switch | [Checkbox](/patterns/forms/checkbox) | ## Selection Patterns (5 or more options) | Pattern | Best For | Avoid When | Key Features | Related | | -------------------------------------------------- | ---------------------------------- | -------------------- | ----------------- | -------------------------------------------- | | [Dropdown](/patterns/forms/selection-input) | ✅ Limited space
✅ 5-15 options | ❌ Multiple selection | ✅ Compact | [Radio](/patterns/forms/radio) | | [Autocomplete](/patterns/forms/autocomplete) | ✅ Many options
✅ Search needed | ❌ Few options | ✅ Search & filter | [Search Field](/patterns/forms/search-field) | | [Multi-select](/patterns/forms/multi-select-input) | ✅ Multiple items
✅ Tags needed | ❌ Single choice | ✅ Bulk selection | [Checkbox](/patterns/forms/checkbox) | ## Text Input Patterns | Pattern | Best For | Avoid When | Key Features | Related | | --------------------------------------------- | ----------------------------------- | -------------- | -------------- | ----------------------------------------------- | | [Text Field](/patterns/forms/text-field) | ✅ Short text
✅ Single line | ❌ Long content | ✅ Simple input | [Rich Text](/patterns/forms/rich-text-editor) | | [Rich Text](/patterns/forms/rich-text-editor) | ✅ Formatted text
✅ Long content | ❌ Simple text | ✅ Formatting | [Text Field](/patterns/forms/text-field) | | [Password](/patterns/forms/password) | ✅ Secure entry
✅ Credentials | ❌ Public data | ✅ Masked input | [Code Input](/patterns/forms/code-confirmation) | | [Search Field](/patterns/forms/search-field) | ✅ Content search
✅ Filtering | ❌ Exact match | ✅ Quick search | [Autocomplete](/patterns/forms/autocomplete) | ## Specialized Input Patterns | Pattern | Best For | Avoid When | Key Features | Related | | ----------------------------------------------- | ------------------------------------ | ----------------- | --------------- | ----------------------------------------------------------- | | [Currency](/patterns/forms/currency-input) | ✅ Money values
✅ Formatting | ❌ Plain numbers | ✅ Auto-format | [Text Field](/patterns/forms/text-field) | | [Phone](/patterns/forms/phone-number) | ✅ Phone numbers
✅ Formatting | ❌ Plain text | ✅ Validation | [Text Field](/patterns/forms/text-field) | | [Color Picker](/patterns/forms/color-picker) | ✅ Color selection
✅ Visual input | ❌ Text input | ✅ Visual picker | [Dropdown](/patterns/forms/selection-input) | | [Rating](/patterns/forms/rating-input) | ✅ User ratings
✅ Quick input | ❌ Precise numbers | ✅ Star scale | [Radio](/patterns/forms/radio) | | [Code Input](/patterns/forms/code-confirmation) | ✅ 2FA/OTP
✅ Verification | ❌ Regular input | ✅ Auto-advance | [Password](/patterns/forms/password) | | [File Input](/patterns/forms/file-input) | ✅ File uploads
✅ Multiple files | ❌ Text input | ✅ File select | [Drag and Drop](/patterns/content-management/drag-and-drop) | ## Date & Time Patterns | Pattern | Best For | Avoid When | Key Features | Related | | ------------------------------------------ | ---------------------------------------- | --------------- | -------------- | ------------------------------------------ | | [Date Input](/patterns/forms/date-input) | ✅ Basic date entry
✅ Known format | ❌ Visual needed | ✅ Direct entry | [Date Picker](/patterns/forms/date-picker) | | [Date Picker](/patterns/forms/date-picker) | ✅ Visual dates
✅ Calendar needed | ❌ Quick entry | ✅ Calendar UI | [Date Range](/patterns/forms/date-range) | | [Date Range](/patterns/forms/date-range) | ✅ Period selection
✅ Start/end dates | ❌ Single date | ✅ Range select | [Date Picker](/patterns/forms/date-picker) | ## Content Management Patterns | Pattern | Best For | Avoid When | Key Features | Related | | ----------------------------------------------------------- | ----------------------------------------- | ------------------- | ------------------------ | ------------------------------------------------------- | | [Accordion](/patterns/content-management/accordion) | ✅ Collapsible sections
✅ Space saving | ❌ Always visible | ✅ Progressive disclosure | [Modal](/patterns/content-management/modal) | | [Modal](/patterns/content-management/modal) | ✅ Focused tasks
✅ Important actions | ❌ Frequent access | ✅ Focus trap | [Tooltip](/patterns/content-management/tooltip) | | [Carousel](/patterns/content-management/carousel) | ✅ Multiple items
✅ Limited space | ❌ Comparison needed | ✅ Progressive reveal | [Infinite Scroll](/patterns/navigation/infinite-scroll) | | [Tooltip](/patterns/content-management/tooltip) | ✅ Extra info
✅ Quick help | ❌ Critical info | ✅ Context help | [Modal](/patterns/content-management/modal) | | [Drag and Drop](/patterns/content-management/drag-and-drop) | ✅ Reordering
✅ Visual sorting | ❌ Simple selection | ✅ Direct manipulation | [Selection Input](/patterns/forms/selection-input) | ## Navigation Patterns | Pattern | Best For | Avoid When | Key Features | Related | | ------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | [Back to Top](/patterns/navigation/back-to-top) | ✅ Long pages
✅ Quick return | ❌ Short content
❌ Mobile-first designs | ✅ Quick navigation
✅ One-click access | [Infinite Scroll](/patterns/navigation/infinite-scroll) | | [Breadcrumb](/patterns/navigation/breadcrumb) | ✅ Deep hierarchies
✅ Complex sites
✅ E-commerce | ❌ Flat structures
❌ Single-level sites | ✅ Location awareness
✅ Easy backtracking | [Navigation Menu](/patterns/navigation/navigation-menu) | | [Infinite Scroll](/patterns/navigation/infinite-scroll) | ✅ Content feeds
✅ Continuous flow
✅ Social media | ❌ Structured content
❌ Goal-oriented tasks | ✅ Auto-loading
✅ Seamless browsing | [Pagination](/patterns/navigation/pagination)
[Load More](/patterns/navigation/load-more) | | [Load More](/patterns/navigation/load-more) | ✅ Content exploration
✅ User control | ❌ Large datasets
❌ Sequential content | ✅ Manual loading
✅ Performance friendly | [Infinite Scroll](/patterns/navigation/infinite-scroll)
[Pagination](/patterns/navigation/pagination) | | [Pagination](/patterns/navigation/pagination) | ✅ Large datasets
✅ Structured content | ❌ Short lists
❌ Continuous reading | ✅ Clear boundaries
✅ Better orientation | [Load More](/patterns/navigation/load-more)
[Infinite Scroll](/patterns/navigation/infinite-scroll) | | [Hamburger Menu](/patterns/navigation/hambuger-menu) | ✅ Mobile interfaces
✅ Space-saving | ❌ Desktop-first
❌ Critical navigation | ✅ Compact
✅ Expandable | [Navigation Menu](/patterns/navigation/navigation-menu)
[Sidebar](/patterns/navigation/sidebar) | | [Megamenu](/patterns/navigation/megamenu) | ✅ Large sites
✅ Complex hierarchies | ❌ Simple navigation
❌ Mobile interfaces | ✅ Rich content
✅ Category overview | [Navigation Menu](/patterns/navigation/navigation-menu) | | [Navigation Menu](/patterns/navigation/navigation-menu) | ✅ Primary navigation
✅ Site structure | ❌ Deep hierarchies
❌ Complex categories | ✅ Clear structure
✅ Easy access | [Megamenu](/patterns/navigation/megamenu) | | [Sidebar](/patterns/navigation/sidebar) | ✅ Dashboard layouts
✅ App interfaces | ❌ Content-heavy sites
❌ Mobile-first | ✅ Persistent nav
✅ Context retention | [Navigation Menu](/patterns/navigation/navigation-menu) | | [Tabs](/patterns/navigation/tabs) | ✅ Related content
✅ Switching views | ❌ Deep hierarchies
❌ Many sections | ✅ Content grouping
✅ Quick switching | [Navigation Menu](/patterns/navigation/navigation-menu) | | | | | | | For implementation details and best practices, visit our [Getting Started](/patterns/getting-started) guide. # CONTENT-MANAGEMENT: [Accordion](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/content-management/accordion) Create effective accordion components for your web applications. Learn best practices for implementing expandable content sections with proper accessibility and keyboard support. # Accordion ***(Also called collapsible panels)*** ## Overview An **accordion** is a UI component that consists of a vertically stacked list of headers that can be expanded or collapsed to reveal or hide related content. It helps conserve screen space by displaying content in a structured and interactive way. Accordions are commonly used for **FAQs, settings panels, and structured content** where users need to access multiple sections without scrolling through all the information at once. ## Use Cases ### When to use: Use an accordion when you need to present **structured content that benefits from progressive disclosure**. **Common use cases include:** * **FAQs (Frequently Asked Questions)** – Helps users find answers quickly. * **Settings and Preferences** – Organizes options into collapsible categories. * **Product Details or Features** – Allows users to expand sections they are interested in. * **Documentation or Guides** – Presents step-by-step content in an organized way. * **Navigation and Filtering** – Used in sidebars for hierarchical content. ### When not to use: * If **all content needs to be visible at once** (e.g., comparison tables). * When **content is too short**—collapsing small amounts of text may reduce usability. * If frequent **switching between sections is necessary**—a tabbed interface might be better. * When users need to **view multiple sections at the same time** (e.g., Terms and Conditions) —consider popovers, modals, or side panels instead. * If content requires **deep nesting of multiple levels**, a structured outline or table of contents may work better. ## Benefits * **Saves space** by showing only relevant content when needed. * **Improves readability** by reducing visual clutter. * **Enhances usability** by grouping related content. * **Optimizes mobile experiences** by minimizing scroll length. ## Drawbacks * **Hides content by default**, requiring extra interaction to access information. * **Can make scanning content harder**, especially if multiple sections are collapsed. * **May not work well for all content types**, particularly if users need to see multiple sections at once. * **Can have accessibility issues** if not correctly implemented with ARIA roles. * **Excessive nesting** of accordions can create a poor user experience. ## Anatomy ```mermaid graph TD A[Accordion] --> B[Accordion Item 1] A --> C[Accordion Item 2] B --> D[Header Trigger 1] B --> E[Accordion Icon 1] B --> F[Content Panel 1] C --> G[Header Trigger 2] C --> H[Accordion Icon 2] C --> I[Content Panel 2] ``` ### Component Structure 1. **Accordion Container** * Wraps all the accordion items. * Handles state management (e.g., open/close behavior). * Should provide appropriate aria-label for screen reader users. 2. **Accordion Item** * A single collapsible section consisting of a header (trigger) and a content panel. 3. **Accordion Header (Trigger)** * The clickable element that expands/collapses the associated content. * Should be a button element for accessibility. * Must contain aria-expanded="true|false" to indicate state. 4. **Accordion Icon** * Provides a visual cue of the accordion state (collapsed or expanded). * Common examples: chevron icons (▼/▲), plus/minus (+/−). * Should rotate or change appearance when toggled. * Must be visually distinguishable and large enough for touch interaction. 5. **Accordion Content Panel** * The collapsible section that appears when triggered. * Should be associated with its header via aria-controls and aria-labelledby. * Must use aria-hidden="true|false" to indicate visibility to screen readers. #### **Summary of Components** | Component | Required? | Purpose | | ------------- | --------- | ------------------------------------------------ | | Container | ✅ Yes | Wraps all accordion items together. | | Item | ✅ Yes | Represents an individual expandable section. | | Trigger | ✅ Yes | Toggles the visibility of the accordion content. | | Icon | ✅ Yes | Indicates open/closed state (e.g., chevron). | | Content Panel | ✅ Yes | Holds the content that expands/collapses. | ## Best Practices ### Content & Usability **Do's ✅** * **Keep headers clear and concise**—they should describe the content inside. * **Use progressive disclosure**—prioritize showing only essential information first. * **Ensure logical grouping**—group related items under the same accordion. * **Maintain consistent styling**—avoid varying sizes or colors for different headers. **Don'ts ❌** * **Don't overload sections**—too much content defeats the purpose of an accordion. * **Avoid unnecessary animations**—fast, smooth transitions improve usability. * **Don't use accordions for essential content**—ensure users can still access key information easily. ### Default Open Behavior **Do's ✅** * **Decide based on user expectations**—if the first section contains critical information, it may be beneficial to start expanded. * **Keep the first accordion open** in **FAQs, tutorials, or onboarding flows** where users need immediate guidance. * **Ensure consistency**—if one accordion is open by default, follow the same pattern across the UI. * **Provide a clear visual indicator** when an accordion is expanded to avoid confusion. **Don'ts ❌** * **Don't force the first section open if the content is non-essential**—let users decide what they need. * **Avoid inconsistent behavior**—mixing some open and some closed sections can be confusing. * **Don't prevent users from collapsing the first accordion**—they should be able to close it if they want. ### Icon Placement & Behavior #### **Placement** **Do's ✅** * **Place the icon at the beginning of the header** for better usability, especially for users relying on screen magnification. * **Ensure the icon remains visually distinguishable**—it should not blend into the text. * **Make sure the icon is keyboard accessible** and updates its state (`aria-expanded`). * **Test different placements** in usability studies to determine what works best for your audience. **Don'ts ❌** * **Avoid placing the icon too far from the trigger text**—users may not associate them. * **Don't rely solely on the icon** to indicate expansion—ensure there is a visual or textual cue as well. * **Avoid animations that make the icon movement too subtle**—it should clearly show state changes. #### **Behavior** **Do's ✅** * **Use an intuitive icon** (e.g., `+` → `−`, or chevron pointing up/down). * **Ensure the icon changes state** when the accordion is expanded or collapsed. * **Animate icon transitions smoothly** (e.g., rotate chevron instead of abruptly changing it). * **Make the icon large enough** to be tappable on mobile devices. **Don'ts ❌** * **Don't rely only on the icon** to indicate expansion—also update `aria-expanded` and visually differentiate expanded sections. * **Avoid using icons that do not clearly indicate** expansion and collapse states. * **Don't use overly complex animations** that slow down interactions. ### Accessibility **Do's ✅** * **Use semantic HTML**—accordion triggers should be `button` elements. * **Implement `aria-expanded`** to indicate open/closed states. * **Ensure focus management**—moving between sections should be intuitive. * **Support keyboard navigation**—allow arrow keys for cycling and `Enter` or `Space` to toggle. **Don'ts ❌** * **Don't trap focus** inside an expanded panel. * **Avoid using `display: none;` on content**—instead, use `visibility` or `aria-hidden` for screen readers. ### Layout & Design **Do's ✅** * **Ensure clear distinctions** between expanded and collapsed states. * **Provide smooth animations** (e.g., height transitions) to improve the user experience. * **Use appropriate spacing** between items to avoid visual clutter. * **Align icons and headers consistently** to maintain a structured appearance. **Don'ts ❌** * **Don't make accordions too small or too large**—users should easily scan headers. * **Avoid inconsistent alignment**—headers, icons, and content should be visually aligned. * **Don't place icons too far from the header text**, making it difficult to associate them with the toggle action. ## Tracking Tracking accordion interactions helps measure user engagement, assess whether users find the hidden content valuable, and determine if sections should be expanded by default. By analyzing user behavior, we can optimize when and how accordions are used. ### Key Tracking Points Each accordion interaction provides valuable insights into user behavior. Below are the key events that should be tracked: | **Event Name** | **Description** | **Why Track It?** | | ------------------------ | --------------------------------------------------------------------- | ---------------------------------------------------------- | | `accordion.view` | When the accordion component enters the viewport. | Determines visibility and content discovery. | | `accordion.expand` | When a user expands an accordion section. | Measures engagement and demand for additional information. | | `accordion.collapse` | When a user collapses an accordion section. | Helps analyze whether users return to a condensed view. | | `accordion.auto_expand` | When a section expands automatically (e.g., pre-expanded by default). | Determines if auto-expansion leads to better engagement. | | `accordion.read_time` | The time a user spends with the expanded content visible. | Helps measure content consumption. | | `accordion.all_expand` | When a user expands **all** sections at once (if supported). | Indicates if users prefer all content visible upfront. | | `accordion.all_collapse` | When a user collapses **all** sections at once. | Tracks behavior when content is condensed back. | ### Event Payload Structure To ensure consistent tracking, here’s a recommended event format: ```json ``` ### Key Metrics to Analyze Once tracking is in place, the following metrics provide actionable insights: * **Expand Rate** → Percentage of users who expand at least one section. * **Collapse Rate** → Percentage of users who collapse a section after expanding it. * **Average Read Time** → How long users keep an expanded section open. * **Auto-Expand vs. Manual Expand Rate** → Helps assess whether users prefer content pre-expanded or manually triggered. * **Multi-Expand Rate** → Percentage of users expanding multiple sections in a session. ### Insights & Optimization Based on Tracking By analyzing tracking data, we can optimize the accordion experience: * 🚨 **Low Expand Rate?** → Users may not notice the accordion sections or find them unnecessary. **Optimization:** Improve section titles for clarity, make expansion triggers more prominent, or test making key sections pre-expanded. * ⏳ **Short Read Time After Expand?** → Users may not be engaging with the expanded content. **Optimization:** Ensure content is concise, scannable, and well-structured. Test alternative formats such as inline content or tabs. * 🔄 **High Collapse Rate?** → Users might be overwhelmed by too much content or prefer a more condensed view. **Optimization:** Reduce section length, highlight key takeaways in the collapsed state, or introduce progressive disclosure. * 🔁 **High Multi-Expand Rate?** → Users frequently expand multiple sections, which may indicate that all content is relevant. **Optimization:** Consider whether an **accordion** is the right UI choice, or if a fully expanded layout would improve readability. * ⚙️ **Auto-Expand Not Leading to Higher Engagement?** → Automatically expanded sections may be ignored. **Optimization:** A/B test auto-expanded vs. manually triggered content to determine user preference. By continuously monitoring these metrics, we can refine accordion usability, ensuring users efficiently access necessary information while avoiding unnecessary interactions. ## Code Example ### **Method 1: Using `

When should I use an accordion?

``` **Pros ✅** * Full styling flexibility—no browser-imposed limitations. * Explicit aria-expanded handling—better screen reader support. * More customization options—e.g., "only one section open at a time" behavior. **Cons ❌** * Requires JavaScript to toggle states. * More implementation complexity compared to `
`. ### **Method 2: Using `
` and `` (Native Approach)** This approach leverages **native browser behavior** without requiring JavaScript. ```html

Frequently Asked Questions

What is an accordion?

An accordion is a UI component that allows users to expand and collapse sections of content.

How does it improve user experience?

Accordions help reduce clutter and make information easier to digest, enhancing the overall user experience.

``` **Pros ✅** * No JavaScript required—fully functional with just HTML & CSS. * Keyboard accessible by default—users can navigate with Tab and toggle with Enter. * Simpler implementation with native support. **Cons ❌** * Limited styling control—some browsers restrict `` styling. * No aria-expanded state by default—some screen readers may not properly announce expansion. * All items can be expanded at once—doesn't support "only one section open" behavior. ### When to use a tabbed carousel vs grouped carousel? Use the **decision tree** below to determine the right method: ```mermaid graph TD A[Do you need full control over styling and behavior?] -->|Yes| B[Use Button + ARIA Accordion] A -->|No| C[Do you want a native solution with minimal code?] C -->|Yes| D[Use Native
Accordion] C -->|No| B[Use Button + ARIA Accordion] ``` For a detailed breakdown of feature differences, refer to the table below: | Feature | `
` Accordion | ` ``` **Pros ✅** * **Full styling control**—can be completely customized with CSS. * **Supports advanced positioning and animations**. * **Can include complex interactions and behaviors**. * **Compatible with all browsers**, including older versions. **Cons ❌** * **Requires JavaScript**—needs scripting for open/close behavior and positioning. * **Manual accessibility management**—requires careful implementation of ARIA attributes and keyboard interactions. * **Positioning challenges**—may require additional libraries or complex logic for proper placement. * **No built-in light dismiss**—must be implemented manually. ### Method 2: Native Popover API ```html

Popover Title

Popover content goes here...

``` **Pros ✅** * **Built-in popover behavior**—handles showing/hiding automatically. * **Light dismiss support**—closes when clicking outside by default. * **Keyboard accessible by default**—supports `Escape` key to close. * **Simpler implementation**—requires minimal JavaScript. * **Stacking context management**—handles z-index automatically. **Cons ❌** * **Limited browser support**—not available in all browsers yet. * **Less control over positioning**—limited options for custom placement. * **Styling restrictions**—some default styles may be harder to override. * **Less flexibility for complex behaviors**—may require additional scripting for advanced use cases. ### When to use Native Popover API vs Custom Popover? ```mermaid graph TD A[Do you need advanced positioning or complex interactions?] -->|Yes| B[Use Custom Popover with ARIA] A -->|No| C[Is browser support for Popover API sufficient for your needs?] C -->|Yes| D[Use Native Popover API] C -->|No| B[Use Custom Popover with ARIA] ``` For a detailed breakdown of feature differences, refer to the table below: | Feature | Native Popover API | Custom Popover with ARIA | | ------------------------- | ------------------------------------------- | -------------------------------------------------- | | **Requires JavaScript?** | ❌ No (for basic behavior) | ✅ Yes (for positioning and interactions) | | **Full styling control?** | ❌ Limited (some default styles) | ✅ Yes (complete control over appearance) | | **Positioning options?** | ❌ Limited (uses default positioning) | ✅ Flexible (can use custom positioning logic) | | **Light dismiss?** | ✅ Built-in | ❌ Must be implemented manually | | **Browser support?** | ❌ Limited (newer browsers only) | ✅ Works in all browsers with JS support | | **Accessibility?** | ✅ Good (but may need enhancements) | ✅ Can be fully accessible (requires careful impl.) | | **Complex interactions?** | ❌ Limited (may need additional JS) | ✅ Supports complex custom behaviors | | **Best for** | Simple popovers with modern browser support | Custom popovers with specific design requirements | ## Accessibility ### ARIA Attributes **Required ARIA attributes:** * `aria-haspopup="true"` on the trigger element. * `aria-expanded` on the trigger element to reflect open/closed state. * `role="dialog"` (or `role="menu"` if used as a menu) on the popover container. * Ensure focus management so that keyboard users receive context. ### Keyboard Interaction Pattern The following table outlines the standard keyboard interactions for popover components. | Key | Action | | --- | --------------------------------------------------------- | | Tab | Navigate between focusable items within the popover | | Esc | Close the popover and return focus to the trigger element | ## SEO * Ensure the popover content is not critical for SEO or provide alternate ways for search engines to access the content. * Use descriptive hidden text if necessary so screen readers can still announce key information. ## Testing Guidelines ### Functional Testing **Should ✓** * [ ] Verify that clicking the trigger displays the popover. * [ ] Ensure that keyboard navigation (Tab, Esc) behaves as expected. * [ ] Confirm ARIA attributes update correctly when toggling the popover. * [ ] Ensure focus handling moves into and out of the popover appropriately. ### Accessibility Testing **Should ✓** * [ ] Validate that screen reader users are notified when the popover is opened. * [ ] Test that focus is not lost when navigating through popover content. * [ ] Ensure the popover closes with the Esc key and returns focus to the trigger. ### Visual Testing **Should ✓** * [ ] Confirm that the popover appears near the trigger and does not obscure other critical information. * [ ] Validate that styling and animations are smooth and non-distracting. * [ ] Check that the popover remains fully visible on different screen sizes. ### Performance Testing **Should ✓** * [ ] Ensure that opening and closing the popover does not induce performance lags. * [ ] Verify that the dynamic positioning adapts swiftly as the viewport changes. ## Design Tokens These design tokens follow the [Design Tokens Format](https://design-tokens.github.io/community-group/format/) specification and can be used with various token transformation tools to generate platform-specific variables. ### Popover Tokens in DTF Format ```json:popover.json { "$schema": "https://design-tokens.org/schema.json", "popover": { "container": { "background": , "border": , "shadow": , "padding": }, "arrow": { "size": , "color": }, "transition": } } ``` ## Related Patterns Consider these related patterns when implementing popovers: * [Modal](/patterns/content-management/modal) - Used for critical interactions requiring full focus. * [Tooltip](/patterns/content-management/tooltip) - Similar in providing contextual information but less interactive. * [Selection Input / Dropdown](/patterns/forms/selection-input) - Best for more complex navigation menus. ## Frequently Asked Questions ## Resources ### Articles ### Documentation [popover | MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/popover) ### Libraries * [Popover - shadcn/ui](https://ui.shadcn.com/docs/components/popover) * [Popover - OriginUI](https://originui.com/popover) # CONTENT-MANAGEMENT: [Tooltip](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/content-management/tooltip) Implement effective tooltip components in your web applications. Learn best practices for contextual help, positioning strategies, and accessibility considerations. # Tooltip ***(Also called hover hint, info bubble)*** ## Overview A **tooltip** is a small popup that provides additional contextual information when a user hovers over, focuses on, or interacts with an element. It helps clarify elements with **icons, buttons, or text snippets** that may not be self-explanatory. There are **two types of tooltips**: * **Simple Tooltips** – Short text descriptions that appear on hover or focus, providing a brief explanation. * **Rich Tooltips** – Enhanced tooltips that may contain **formatted text, icons, images, or interactive elements**. Tooltips should be used to enhance understanding without overwhelming the user interface. ## Use Cases ### When to use: Use a tooltip when you need to provide **additional context or explanations** without taking up extra space in the UI. **Common use cases include:** **Simple Tooltips** * **Clarifying icons or abbreviations** (e.g., a settings cog, currency symbols). * **Providing additional information** about form fields or table headers. * **Showing helper text** for complex actions (e.g., "This action is permanent"). * **Explaining disabled elements** when a user cannot interact with them. * **Providing keyboard shortcuts** when hovering over action buttons. **Rich Tooltips** * **Providing in-depth explanations** beyond a brief description. * **Displaying small images, formatted text, or interactive content**. * **Presenting additional details about data points in charts**. * **Showing user profile previews in social apps**. ### When not to use: * **For critical information** users must read, such as error messages. * **For content that should remain visible**, like persistent hints or descriptions. * **When users need to interact** with the tooltip itself. * **If the tooltip is the only means** of conveying information (accessibility issue). * **For mobile-first interactions** where hover-based behavior isn't intuitive. ## Benefits * **Reduces clutter** by providing contextual information without crowding the UI. * **Improves user understanding** of complex actions or terminology. * **Enhances accessibility** when used correctly with keyboard and screen reader support. * **Provides instant feedback** without disrupting the user's flow. ## Drawbacks * Can be **difficult to trigger** on mobile devices due to the lack of hover interactions. * Often **overlooked by users**, especially if they don't expect additional information. * May **interfere with content visibility**, particularly if not positioned well. * Can cause **accessibility issues** if not properly implemented for keyboard and screen readers. * If tooltips **disappear too quickly**, users may struggle to read the content. ## Anatomy ## Anatomy ```mermaid graph TD A[Tooltip] --> B[Trigger Element] B -->|Hover/Focus| C[Tooltip Box] C --> D[Tooltip Content] C --> E[Optional Interactive Elements] ``` ### Component Structure 1. **Trigger Element** * The interactive element (e.g., button, icon, text) that activates the tooltip. * Should have **`aria-describedby`** linking to the tooltip content for accessibility. * Can be activated by **hover (mouse), focus (keyboard), or tap (touch devices)**. * Should have a **clear focus indicator** when navigated via keyboard. 2. **Tooltip Box** * The container that appears when the tooltip is activated. * Should be **positioned near the trigger element** for contextual relevance. * Should have **`role="tooltip"`** for proper screen reader support. 3. **Tooltip Content** * Contains the **explanatory text or information**. * Should be **short and concise** to avoid overwhelming users. * Should **not contain interactive elements** like links or buttons in simple tooltips. 4. **Arrow (Optional)** * A **visual pointer** indicating the tooltip's source. * Adjusts dynamically **based on the tooltip's position** (e.g., top, bottom, left, right). 5. **Optional Interactive Elements (For Rich Tooltips)** * Some tooltips allow **links, buttons, or other interactive elements**. * Requires **`aria-haspopup="true"` and `aria-expanded="true|false"`** for accessibility. * Should **remain open while interacting** and dismiss only when clicking outside or pressing `Esc`. 6. **Dismiss Behavior** * Simple tooltips **should disappear on mouse-out, focus loss, or tap elsewhere**. * Rich tooltips **should remain open until dismissed manually**. #### **Summary of Components** | Component | Required? | Purpose | | -------------------- | --------- | ---------------------------------------------- | | Trigger Element | ✅ Yes | The element that triggers the tooltip. | | Tooltip Box | ✅ Yes | Contains the tooltip message. | | Tooltip Content | ✅ Yes | Displays a short explanatory message. | | Arrow | ❌ No | Visually connects the tooltip to the trigger. | | Interactive Elements | ❌ No | Enables links or buttons inside rich tooltips. | | Dismiss Behavior | ✅ Yes | Defines how and when the tooltip should close. | ## Best Practices ### Content **Do's for Simple Tooltips ✅** * **Keep concise**—**1-2 sentences max** to provide quick context. * **Trigger on hover and focus** for accessibility. * **Position strategically** to **avoid covering nearby elements**. **Do's for Rich Tooltips ✅** * **Use when additional context is needed** (e.g., explanations, formatted text). * **Ensure it remains visible until dismissed**, if interactive. * **Allow keyboard navigation** if containing buttons or links. **Don'ts ❌** * **Avoid tooltips for critical information**—users might miss them. * **Don't overuse long tooltips**—consider using a popover or [modal](/patterns/content-management/modal). * **Avoid adding interactive elements** (buttons, links) inside tooltips unless using an accessible popover. ### Accessibility **Do's for Simple Tooltips ✅** * **Ensure they appear on `focus` as well as hover**. * **Use `aria-describedby`** on the trigger element to associate it with the tooltip. * **Provide `role="tooltip"`** for proper screen reader support. **Do's for Rich Tooltips ✅** * **If interactive, use `aria-haspopup="true"`** and **`aria-expanded="true|false"`**. * **Allow users to dismiss using Escape key**. * **Ensure users can tab into and out of the tooltip seamlessly**. **Don'ts ❌** * **Don't rely only on hover-based activation**—ensure focus also triggers tooltips. * **Avoid auto-closing tooltips too quickly**, which may frustrate users. * **Don't position tooltips in a way that obstructs other content**. ### Visual Design **Do's ✅** * **Use subtle animations** (fade-in, fade-out) for smooth appearance. * **Ensure tooltips have readable font sizes** (at least `14px`). * **Maintain sufficient padding and spacing** for easy readability. * **Use arrows or indicators** to clearly point to the related element. **Don'ts ❌** * **Avoid excessive delays in showing tooltips**—users should see them instantly. * **Don't use tooltips that disappear too quickly** before users can read them. * **Avoid distracting animations** that hinder usability. ### Performance Optimization **Do's ✅** * **Lazy-load tooltips** to reduce initial page load impact. * **Use CSS for animations** (`opacity`, `transform`) instead of JavaScript. * **Minimize reflows and repaints** when tooltips appear or disappear. **Don'ts ❌** * **Avoid excessive event listeners** that degrade performance. * **Don't trigger tooltips on every mouse movement**—use `mouseenter` instead of `mousemove`. ### Common Mistakes & Anti-Patterns #### Tooltips That Disappear Too Fast **❌ What’s Wrong?** Users might not have enough time to read the tooltip before it disappears. **How to Fix It?** Ensure tooltips remain visible **for at least 3–5 seconds** or stay open on hover. *** #### Not Accessible via Keyboard **❌ What’s Wrong?** Many tooltips rely only on hover, making them inaccessible to keyboard users. **How to Fix It?** Ensure tooltips can be triggered \*\*via focus (`Tab` key)`**. For screen readers, pair `aria-describedby`on the trigger element with`role="tooltip"\` on the tooltip container. *** #### Blocking Important Content **❌ What’s Wrong?** Tooltips that cover input fields or buttons create confusion and may block clicks or taps. **How to Fix It?** Position tooltips **away from interactive elements** and use arrow indicators to point from the trigger to the tooltip. *** #### Overloading with Too Much Text **❌ What’s Wrong?** Long tooltips become unreadable, especially for screen readers that have to announce everything at once. **How to Fix It?** Keep tooltips **brief (max 2 lines)**. For more details, link to a help page or open a larger popover or modal instead. *** #### Not Announced by Screen Readers (Accessibility) **❌ What’s Wrong?** Tooltips that appear on mouse hover but lack ARIA attributes aren’t announced to screen reader users. **How to Fix It?** Use `role="tooltip"` for the tooltip element and link it to the trigger with `aria-describedby="tooltipId"`. Keep the tooltip in the DOM while it’s visible so assistive tech can detect it. *** #### Insufficient Color Contrast or Tiny Font (Accessibility) **❌ What’s Wrong?** Text that’s too small or low-contrast is difficult for users with low vision to read. **How to Fix It?** Maintain a **4.5:1** color contrast ratio (minimum) and use a **legible font size** (usually at least 14–16px). Test with browser zoom to ensure the tooltip scales properly. ## Tracking Tracking tooltip interactions helps measure their effectiveness, determine whether users find them useful, and identify potential usability issues. By analyzing tooltip engagement, we can assess whether tooltips enhance comprehension or if users ignore them. ### Key Tracking Points Each tooltip interaction provides valuable insights into user behavior. Below are the key events that should be tracked: | **Event Name** | **Description** | **Why Track It?** | | -------------------------- | --------------------------------------------------------------------- | --------------------------------------------------- | | `tooltip.view` | When the tooltip first appears (hover, focus, or auto-triggered). | Determines how often users see tooltips. | | `tooltip.auto_open` | When a tooltip appears automatically without user action. | Helps assess if tooltips are too intrusive. | | `tooltip.hover_open` | When a user opens a tooltip by hovering over a trigger element. | Tracks hover-based interactions. | | `tooltip.focus_open` | When a tooltip opens via keyboard focus. | Ensures accessibility engagement is measured. | | `tooltip.click_open` | When a tooltip opens via a user click (if applicable). | Measures intentional user engagement. | | `tooltip.close` | When a tooltip is dismissed (moving cursor away, pressing Esc, etc.). | Tracks how users exit tooltips. | | `tooltip.interaction_time` | The time a user spends viewing the tooltip before closing it. | Helps determine if tooltips are helpful or ignored. | ### Event Payload Structure To ensure consistent tracking, here’s a recommended event format: ```json ``` ### Key Metrics to Analyze Once tracking is in place, the following metrics provide actionable insights: * Tooltip View Rate → Percentage of users who trigger a tooltip. * Hover vs. Focus Activation Rate → Compares how users open tooltips (mouse vs. keyboard). * Dismissal Rate → Percentage of users who close the tooltip quickly. * Average Interaction Time → How long users keep the tooltip open. * Repeated Views Per User → Indicates if users need repeated clarification. ### Insights & Optimization Based on Tracking By analyzing tracking data, we can optimize tooltip behavior: * 🚨 **Low Tooltip View Rate?** → Users might not notice tooltips or may not need them. **Optimization:** Ensure triggers are visually clear, adjust placement, or test if an inline explanation is more effective. * ⏳ **Short Interaction Time?** → Users might be dismissing tooltips too quickly without reading them. **Optimization:** Simplify content, increase font size, or extend the display duration before auto-hiding. * 📉 **High Dismissal Rate?** → Tooltips may be appearing at the wrong time, covering important content, or distracting users. **Optimization:** Adjust positioning, delay appearance, or use persistent inline text instead of a tooltip. * 🎯 **Low Focus Activation Rate?** → Keyboard users may struggle to access tooltips, indicating accessibility issues. **Optimization:** Ensure proper **ARIA attributes** (`aria-describedby`), focus management, and keyboard navigation support. * 🔄 **Frequent Repeated Views?** → Users may not fully understand the tooltip content. **Optimization:** Improve clarity, rewrite text concisely, or add supporting visuals like icons or links to more detailed help content. By continuously monitoring these metrics, we can refine tooltip usability and ensure they provide **real value** rather than unnecessary friction. ## Code Examples ### Basic Implementation ```html ``` ## Accessibility ### Keyboard Interaction Pattern The following table outlines the standard keyboard interactions for tooltip components. These interactions ensure that users can access and dismiss tooltips effectively using only a keyboard. | Key | Action | | ----------- | ------------------------------------------------------------------------------------------------ | | Tab | Moves focus to the element that triggers the tooltip. The tooltip should appear on focus. | | Shift + Tab | Moves focus to the previous interactive element. The tooltip should close when focus moves away. | | Escape | Dismisses the tooltip manually (if dismissible). | | Enter/Space | Activates the tooltip (for tooltips that require explicit activation). | > **Note**: Tooltips should appear when an element **receives focus** (for keyboard users) and **disappear when focus moves away**. If a tooltip is **interactive** (contains links or buttons), it must be dismissible via the `Escape` key. ## Testing Guidelines ### Functional Testing **Should ✓** * [ ] Ensure the tooltip **appears on hover, focus, and touch activation**. * [ ] Verify the tooltip **disappears when focus is removed** or the user moves the cursor away. * [ ] Test that tooltips **do not obstruct important content** when displayed. * [ ] Confirm that tooltips **adapt properly on different screen sizes**. * [ ] Validate that tooltips **do not break layout or cause visual glitches**. ### Accessibility Testing **Should ✓** * [ ] Ensure tooltips are **keyboard accessible** (triggered via `Tab` key). * [ ] Verify that tooltips are **announced by screen readers** when triggered. * [ ] Confirm `aria-describedby` **correctly links tooltips to their respective elements**. * [ ] Check that tooltips **persist long enough** for screen reader users to read. * [ ] Ensure **sufficient color contrast** between tooltip text and background. * [ ] Test with `prefers-reduced-motion` enabled to ensure animations are minimized. ### Visual Testing **Should ✓** * [ ] Confirm tooltip text is **legible across all screen sizes**. * [ ] Validate **proper spacing and positioning** of tooltips. * [ ] Test tooltip animations for **smooth appearance and disappearance**. * [ ] Ensure tooltips **do not overlap critical UI elements**. * [ ] Verify tooltips **align properly with their trigger elements**. ### Performance Testing **Should ✓** * [ ] Measure tooltip render performance to **avoid jank or slow animations**. * [ ] Ensure tooltips **lazy-load when necessary** to prevent excessive memory usage. * [ ] Optimize tooltip animations to **use `opacity` and `transform` for smooth rendering**. * [ ] Test for **efficient event handling** to avoid performance degradation on repeated interactions. ## Design Tokens These design tokens follow the [Design Tokens Format](https://design-tokens.github.io/community-group/format/) specification and can be used with various token transformation tools to generate platform-specific variables. ### Tooltip Tokens in DTF Format ```json { "$schema": "https://design-tokens.org/schema.json", "tooltip": { "background": , "textColor": , "padding": , "borderRadius": , "animationDuration": , "maxWidth": , "arrowSize": , "offset": , "shadow": } } ``` ## Related Patterns Consider these related patterns when implementing tooltips: * [Modal](/patterns/content-management/modal) - Used for critical interactions requiring full focus. * [Popover](/patterns/content-management/popover) - Used when the additional content that requires user interaction, such as buttons or form elements, rather than just providing passive information. * [Selection Input / Dropdown](/patterns/forms/selection-input) - Best for more complex navigation menus. ## Frequently Asked Questions ## Resources ### Articles * [Tooltip - Nielsen Norman Group](https://www.nngroup.com/articles/tooltip-guidelines/) * [Designing better tooltips for improved UX - LogRocket Blog](https://blog.logrocket.com/ux-design/designing-better-tooltips-improved-ux/) ### Documentation * [Tooltip Pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/) ### Libraries * [Tooltip - shadcn/ui](https://ui.shadcn.com/docs/components/tooltip) * [Tooltip - Origin UI](https://originui.com/tooltip) # FORMS: [Autocomplete](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/autocomplete) Build user-friendly autocomplete with search suggestions, keyboard navigation, and accessibility features. # Autocomplete ***(Also called Autosuggest)*** ## Overview The **autocomplete** is an interactive input component that helps users quickly find and select values from a predefined list of options as they type. They combine the flexibility of [text input](/patterns/forms/text-field) with dropdown-style selection, providing suggestions that match the user's input in real-time. This pattern reduces errors, speeds up data entry, and improves the overall form completion experience. ## Use Cases ### When to use: * When users need to select from a large set of predefined options (e.g., country selection, airport codes) * When you want to help users find and select options more quickly than scrolling through a long dropdown * When you want to reduce errors by guiding users to valid input options * When the input has a finite set of valid responses that are known in advance * When you want to combine free text input with suggestion functionality ### When not to use: * When there are fewer than 10 options (use a standard dropdown/select instead) * When users need to enter completely free-form text without restrictions * When all options need to be visible at once for comparison * When network latency could significantly delay suggestion results * When the input field requires exact, verbatim text entry (like passwords) ### Common scenarios and examples * **Searching for products** in an e-commerce catalog * **Entering city names** for travel or weather applications * **Looking up user or contact names** in a messaging or collaboration tool ## Benefits * **Speeds up data entry** by narrowing down possible options in real-time * **Reduces user frustration** and guesswork by guiding them to valid options * **Minimizes mistakes** and typos, as suggestions can be confirmed or chosen from a list ## Drawbacks * **Accessibility challenges** – Requires proper ARIA attributes (`aria-expanded`, `aria-controls`, `aria-activedescendant`) for screen readers. * **Keyboard navigation complexity** – Users must be able to navigate the suggestions using arrow keys and select options with Enter. * **Performance issues** – Fetching suggestions dynamically can introduce lag if not optimized with debouncing and caching. * **Overwhelming for users** – Too many suggestions or unclear results can create cognitive overload. * **Implementation effort** – Requires handling both filtering logic and managing suggestion visibility correctly. ## Anatomy ### Component Structure ```mermaid graph TD A[Autocomplete] --> B[Container] B --> C[Input Field] B --> D[Suggestions List] B --> E[Clear Button] C --> F[Label] C --> G[Text Input] C --> H[Loading Indicator] D --> I[Suggestion Items] I --> J[Item 1] I --> K[Item 2] I --> L[Item n...] J --> M[Text Match] J --> N[Additional Info] E --> O[Clear Icon] ``` 1. **Container** * Wraps the entire autocomplete area, including the input and dropdown * Handles positioning, sizing, and possible floating layers for the suggestions 2. **Input** * The text field where users type their query * Provides real-time updates and triggers suggestion fetching 3. **Label** * Optional text label describing the input's purpose * Provides clarity for screen readers and visible context for users 4. **Clear Button** * Allows users to quickly clear the input field * Often represented by an "X" or "✕" icon ## Best Practices ### Content **Do's ✅** * Provide a descriptive label that indicates the purpose of the Autocomplete field * Use placeholder text to show example input (e.g., "Start typing a country...") **Don'ts ❌** * Don't rely on placeholder text as a replacement for a label * Don't make your suggestions so vague that it's unclear what the user is selecting ### Accessibility **Do's ✅** * Use `aria-controls`, `aria-autocomplete`, and other relevant ARIA attributes to help screen readers * Include a visually hidden label or descriptive text if you rely on an icon-only clear button * Add a debounce delay to the input field to avoid triggering a fetch request too often **Don'ts ❌** * Don't remove focus outlines without providing alternative focus indicators * Don't assume all users can use a mouse; ensure keyboard navigation works properly ### Visual Design **Do's ✅** * Keep the suggestion list clearly delineated, with sufficient contrast and spacing * Highlight hovered or focused suggestion items with a distinct visual state **Don'ts ❌** * Don't display an overly large list of suggestions (limit it to a reasonable number), use a scroll bar to allow users to scroll through the list. * Don't create a cluttered or confusing interface by mixing too many design elements ### Layout & Positioning **Do's ✅** * Position the dropdown list immediately below the input field * Ensure suggestions list appears in front of other page elements when open **Don'ts ❌** * Don't hide the list behind overlays or modals * Don't move the dropdown to a completely different area away from the input ## Code Examples ### Basic Implementation ```html
``` ## Design Tokens These design tokens follow the [Design Tokens Format](https://design-tokens.github.io/community-group/format/) specification and can be used with various token transformation tools to generate platform-specific variables. ### Autocomplete Tokens in DTF Format ```json { "$schema": "https://design-tokens.org/schema.json", "Autocomplete": { "container": { "borderRadius": , "background": }, "input": , "suggestionsList": { "maxHeight": , "background": , "itemHoverBg": } } } ``` ## Frequently Asked Questions ## Resources ### Articles * [9 UX Best Practice Design Patterns for Autocomplete Suggestions](https://baymard.com/blog/autocomplete-design) by Baymard Institute * [Best Practices: Designing autosuggest experiences](https://uxmag.com/articles/best-practices-designing-autosuggest-experiences) ## Documentation * [WAI-ARIA: Combobox Pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) # FORMS: [Button](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/button) Create accessible and user-friendly buttons with proper states, design patterns, and implementation guidelines. # Button ## Overview **Buttons** are interactive elements that trigger actions or events when clicked or interacted with. ## Use Cases ### When to use: * To trigger an immediate action or event (e.g., "Save", "Delete", "Send") * To submit a form * To open or close interactive elements (modals, dialogs, menus) * To toggle between states (e.g., play/pause, show/hide) * To download files or content * To navigate between steps in a multi-step process ### When not to use: * For navigation between pages (use links instead) * When the action isn't immediately clear to users * For text-only content that doesn't trigger an action * When the interaction would be better served by a different component (e.g., checkbox, toggle switch) * When multiple conflicting actions are grouped together * When the action requires additional context that isn't immediately available ### Common scenarios and examples * Primary actions: "Submit", "Save", "Continue" * Secondary actions: "Cancel", "Back", "Reset" * Destructive actions: "Delete", "Remove", "Clear All" * Toggle actions: "Show More", "Expand/Collapse", "Play/Pause" * Process actions: "Upload", "Download", "Export" * Social actions: "Share", "Follow", "Like" ## Benefits * Provides clear, actionable interactions for users to accomplish tasks * Maintains consistency in user interface interactions across the application * Offers visual feedback and states (hover, focus, active, disabled) to enhance usability * Supports accessibility through keyboard navigation and screen reader compatibility * Reduces cognitive load by making actions immediately recognizable ## Drawbacks * **Overuse can lead to UI clutter** – Too many buttons in an interface can confuse users. * **Styling inconsistencies** – Needs proper theming and responsive considerations for different screen sizes. * **Click area issues** – If not sized properly, buttons may be difficult to tap on mobile. * **Lack of clear labels** – Buttons without descriptive text (e.g., just an icon) can cause usability problems. * **Focus management** – Requires proper `:focus` states for accessibility and keyboard users. ## Anatomy ```mermaid flowchart TB subgraph Button Container[Container Element] -->|contains| Content[Content Area] Content --> Icon[Icon ] Content --> Label[Label Text] Content --> LoadingSpinner[Loading Spinner ] classDef container stroke:#666,stroke-width:2px class Button container end ``` ### Component Structure 1. **Container** * The root button element that wraps all other components * Handles click events and keyboard interactions * Manages focus states and accessibility attributes * Contains variants for different button styles (default, destructive, outline, etc.) 2. **Label Text** * The button label communicates the action that will occur * Should be clear, concise, and action-oriented * Must maintain proper contrast ratio with the background 3. **Icon (Optional)** * Icons can be added to clarify an action * Should be the same color as the text * Placed on the left side of the label by default * Size should be proportional to text (default 16x16px) * Should include proper ARIA labels when used alone 4. **Loading State (Optional)** * Visual indicator for async operations * Replaces or overlays the button content * Should maintain the button's original width * Prevents multiple clicks during loading * Typically uses a spinner or progress indicator * Add loading text alongside spinners (e.g., "Saving..." vs just a spinner) 5. **Visual States** * Default: Normal state * Hover: Visual feedback on mouse over * Focus: Keyboard navigation indicator * Active: Pressed state * Disabled: Indicates non-interactive state * Loading: Shows processing state ### **Summary of Components** | Component | Required? | Purpose | | ------------- | --------- | --------------------------------------------------------- | | Container | ✅ Yes | Wraps all button elements and handles interactions. | | Label Text | ✅ Yes | Communicates the action that the button performs. | | Icon | ❌ No | Enhances clarity of the action (typically placed left). | | Loading State | ❌ No | Indicates an ongoing process (e.g., saving, submitting). | | Visual States | ✅ Yes | Defines button interactions (hover, focus, active, etc.). | ## Button Variations ### Content Composition 1. **Text Only** ```html ``` 2. **Icon Only** ```html ``` 3. **Icon + Text** * Left Icon ```html ``` * Right Icon ```html ``` 4. **Double Icon** ```html ``` 5. **With Counter/Badge** ```html ``` 6. **With Command/Shortcut** ```html ``` ### Profile Variations 7. **With Avatar** ```html ``` ### Action Groups 8. **Button Groups** * Horizontal Group ```html
``` * Vertical Group ```html
``` 9. **Split Buttons** ```html
``` ### State Variations 10. **Loading States** ```html ``` 11. **Toggle States** ```html ``` ### Social Variations 12. **Social Login** ```html ``` ### Special Purpose 13. **Upload Button** ```html ``` 14. **Numeric Indicator** ```html ``` Each variation can be combined with different visual styles (primary, secondary, outline, ghost) and sizes (small, medium, large) to create the full range of possible button components. ## Best Practices ### Content **Do's ✅** * Use action verbs that describe what the button does (eg: "Save" instead of "Submit") * Keep button labels concise and clear * Be consistent with button labeling across the application * Include loading text when appropriate ("Saving..." vs "Save") * Use sentence case for button labels (e.g., "Save Changes") **Don'ts ❌** * Don't use vague labels like "Click Here" or "Submit" * Don't use inconsistent terminology * Don't write overly long button labels * Don't use technical jargon in button labels * Don't mix different cases in button labels ### Accessibility **Do's ✅** * Use descriptive labels that clearly communicate the action [^describe-buttons] * Provide visual feedback for all interactive states * Ensure keyboard navigation works properly * Include loading states for asynchronous actions * Don't pass the `disabled` attribute to buttons, instead use `aria-disabled`. You would risk disrupting the keyboard navigation flow as this would reset focus on the button. * Use descriptive loading states with both text and visual indicators **Don'ts ❌** * Don't rely solely on color to communicate button states * Don't disable browser focus indicators without providing alternatives * Don't use button elements for navigation (use links instead) * Don't auto-focus destructive actions * Don't remove focus styles ### Visual Design **Do's ✅** * Use the same button style for the same action throughout the application * Make buttons finger-friendly for mobile users (minimum 44x44px touch target) * Use appropriate visual hierarchy (primary, secondary, tertiary buttons) * Maintain consistent spacing between button groups * Use appropriate color contrast ratios (WCAG 2.1 AA compliance) * Include hover and focus states for interactive feedback * Keep icon and text alignment consistent * Maintain consistent padding and height across similar buttons * Scale button size appropriately for different viewport sizes **Don'ts ❌** * Don't have more than one primary action button on the screen at a time * Don't use a [dark pattern](https://www.deceptive.design/) when you don't want users to take a certain action * Don't mix different button styles for the same action type * Don't use colors that conflict with your application's color scheme * Don't make disabled buttons look interactive * Don't use inconsistent corner radius within button groups * Avoid having buttons looking like links or vice versa * Don't use spinners without descriptive text ### Mobile & Touch Considerations **Do's ✅** * Place primary actions within thumb-friendly zones * Use full-width buttons for important actions on mobile * Implement haptic feedback for touch interactions * Maintain sufficient spacing between touch targets (minimum 8px) **Don'ts ❌** * Don't place critical actions in hard-to-reach corners * Don't rely solely on hover states for mobile feedback * Don't make touch targets smaller than 44x44px * Don't crowd multiple buttons together on mobile views ### Layout & Positioning **Do's ✅** * Place primary action buttons in prominent, easily accessible locations * Align buttons consistently within forms and dialogs * Group related buttons together * Consider mobile touch targets (minimum 44x44px) **Don'ts ❌** * Don't position buttons where they might be accidentally clicked * Don't hide important actions behind dropdown menus * Don't place buttons in unexpected locations (e.g., footer) ## Code Examples ### Basic Implementation ```html ``` ### Form Submit Button ```html
``` ## Accessibility ### ARIA Attributes **Required ARIA attributes:** * Use `aria-label` for icon-only buttons * Use `aria-pressed` for toggle buttons * Use `aria-expanded` for buttons that control expandable content * Use `aria-disabled="true"` instead of the `disabled` attribute * Use `aria-describedby` to associate additional descriptive text ### Screen Reader Support **Implementation example:** ```html ``` ### Keyboard Navigation * Buttons must be focusable and activated with both Enter and Space keys * Focus order should follow a logical sequence * Focus states must be clearly visible * Avoid removing focus outlines without providing alternatives * Maintain focus after interactions (e.g., after closing a modal) ## Testing Guidelines ### Functional Testing **Should ✓** * [ ] Show a loader when the button is submitting a form * [ ] Disable the button during form submission to prevent double submissions * [ ] Handle click events and trigger the appropriate action * [ ] Maintain proper visual states (hover, focus, active, disabled) * [ ] Support keyboard interaction (Enter and Space keys) * [ ] Preserve button width when switching between normal and loading states * [ ] Reset to initial state after operation completion ### Accessibility Testing **Should ✓** * [ ] Be focusable and have visible focus indicators * [ ] Have proper ARIA labels, especially for icon-only buttons * [ ] Maintain sufficient color contrast ratios (WCAG 2.1 AA) * [ ] Support screen reader announcements of button state changes * [ ] Be operable with keyboard navigation * [ ] Communicate loading states to assistive technologies * [ ] Have appropriate touch target sizes (minimum 44x44px) ### Visual Testing **Should ✓** * [ ] Maintain consistent styling across different variants (primary, secondary, destructive) * [ ] Display icons with correct alignment and spacing * [ ] Show proper visual feedback for all interactive states * [ ] Render correctly across different viewport sizes * [ ] Handle text overflow appropriately * [ ] Display loading spinners centered within the button * [ ] Maintain proper padding and margins in all states ### Performance Testing **Should ✓** * [ ] Render without layout shifts * [ ] Handle rapid click events appropriately * [ ] Maintain smooth transitions between states * [ ] Load icons and spinners efficiently * [ ] Function without JavaScript (progressive enhancement) ### Testing Tools * Accessibility: [WAVE](https://wave.webaim.org/), [aXe](https://www.deque.com/axe/browser-extensions/), or [Lighthouse](https://developer.chrome.com/docs/lighthouse/overview) * SEO: [Google's Rich Results Test](https://developers.google.com/search/docs/appearance/structured-data) * Performance: [Chrome DevTools Performance panel](https://developer.chrome.com/docs/devtools/performance/overview) * Visual Regression: [Percy](https://percy.io/) or [Chromatic](https://www.chromatic.com/) * Cross-browser: [BrowserStack](https://www.browserstack.com/) or [Sauce Labs](https://saucelabs.com/) ## Browser Support ## Design Tokens These design tokens follow the [Design Tokens Format](https://design-tokens.github.io/community-group/format/) specification and can be used with various token transformation tools to generate platform-specific variables. ### Button Tokens in DTF Format ```json { "$schema": "https://design-tokens.org/schema.json", "button": { "sizing": { "height": , "paddingX": , "iconSize": , "iconGap": , "touchTarget": }, "typography": { "fontFamily": , "fontWeight": , "fontSize": }, "border": { "radius": , "width": }, "variants": { "primary": { "background": { "default": , "hover": , "active": , "disabled": }, "text": { "default": , "disabled": } }, "secondary": { "background": { "default": , "hover": , "active": , "disabled": }, "text": { "default": , "disabled": } }, "destructive": { "background": { "default": , "hover": , "active": , "disabled": }, "text": { "default": , "disabled": } }, "outline": { "border": { "default": , "hover": , "active": , "disabled": }, "text": { "default": , "disabled": } } }, "states": { "focusRing": { "width": , "offset": , "color": }, "loadingSpinner": } } } ``` ## Frequently Asked Questions \` and manage ARIA attributes appropriately.", }, , , ]} /> ## Resources ### Articles * [button: The Button element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) * [I've been doing buttons wrong! Have you?](https://uxplanet.org/ive-been-doing-buttons-wrong-have-you-2117c0066613) by Adham Dannaway * [A comprehensive guide to buttons](https://uxplanet.org/a-comprehensive-guide-to-buttons-8f3b8a1c6f0d) by UX Planet * [A comprehensive guide to designing UX buttons](https://www.invisionapp.com/inside-design/comprehensive-guide-designing-ux-buttons/?ref=checklist.design) by InVision * [Building Accessible Buttons with ARIA: A11y Support Series](https://www.deque.com/blog/accessible-aria-buttons/) by Deque * [Buttons A11y Styleguide](https://a11y-style-guide.com/style-guide/section-general.html#kssref-general-buttons) ### Design systems * [Style Dictionary](https://styledictionary.com/) * [Button (Carbon Design System)](https://carbondesignsystem.com/components/button/usage/) * [Button (Material Design)](https://m3.material.io/components/all-buttons) ### Libraries [Button - Origin UI](https://originui.com/button) ### Footnotes [^describe-buttons]: [Descriptive buttons](https://primer.style/guides/accessibility/descriptive-buttons) # FORMS: [Checkbox](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/checkbox) Learn how to implement accessible checkbox inputs in your web applications. Discover best practices for multiple selection controls, states handling, and accessibility. # Checkbox ## Related components * Only one selection: [Radio button](/patterns/forms/radio) * On and Off option [Toggle](/patterns/forms/toggle) # FORMS: [Code Confirmation](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/code-confirmation) Implement user-friendly code confirmation inputs for verification codes and OTPs. Learn best practices for segmented inputs, auto-focus behavior, and accessibility. # Code Confirmation ![2FA Code Confirmation](/patterns/code-confirmation/do/paypal.jpg) *Good example of 2FA code confirmation screen from PayPal* # FORMS: [Color Picker](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/color-picker) Select colors with visual feedback # Color Picker # FORMS: [Currency Input](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/currency-input) Create currency input fields with number formatting and international currency handling. # Currency Input ### Internationalization Beyond Localization * **Currency Formatting** → Adapt for region-specific formats (e.g., `$1,299.99 USD` vs. `1.299,99 € EUR`). # FORMS: [Date Input](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/date-input) Build date input fields with validation, formatting, and localization features. # Date Input # FORMS: [Date Picker](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/date-picker) Create user-friendly date pickers with calendar interfaces and keyboard navigation. # Date Picker # FORMS: [Date Range](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/date-range) Build date range selection with calendar interfaces and validation features. # Date Range # FORMS: [File Input](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/file-input) Create user-friendly file upload components for your web applications. Learn best practices for file selection, drag-and-drop, progress indicators, and validation. # File Input # FORMS: [Form Validation](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/form-validation) Learn how to implement effective form validation in your web applications. Discover best practices for error handling, real-time validation, and user feedback. # Form Validation ## Comparison of Required Field Marking Methods | Alternative | Description | Pros ✅ | Cons ❌ | | ----------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **1️⃣ Explicit "Required" Label** | Displays **"(Required)"** next to the label. | - Works for **all users**, including screen readers and color-blind users.
- No need for extra ARIA attributes. | - Takes slightly more space in the UI. | | **2️⃣ Asterisk (\*) with ARIA Explanation** | Uses **`*`** but adds an `aria-describedby` explanation. | - Keeps UI cleaner while maintaining accessibility.
- Screen readers announce **"Fields marked with an asterisk are required."** | - **Requires additional explanation** (`aria-describedby`).
- **Without the extra message, asterisks alone are not accessible**. | | **3️⃣ Required Field with Visually Hidden Text** | Uses a **hidden label** for screen readers but remains minimal visually. | - **Looks clean visually** while still accessible.
- **Screen readers announce it as "Email Required"**. | - **Not visible for sighted users** who rely on visual cues. | | **4️⃣ Required Field with an Inline Icon + Tooltip** | Uses **an asterisk (\*) inside a focusable icon** with a tooltip. | - **Visually clear** while keeping text minimal.
- Works well when paired with a **tooltip on hover or focus**. | - **Requires CSS for styling** (ensuring asterisks are not the only indicator).
- Users **might not see tooltip hints** if they don't hover over the icon. | | **5️⃣ Required Field with `required` Attribute Only** | Uses only the `required` attribute without visible markers. | - Works well for **basic validation**.
- Screen readers **will announce the field as required**. | - No **visible indicator for sighted users** before form submission.
- **Errors only appear after submission**, which may confuse users.
- Some browsers may **not enforce required fields consistently**. | # FORMS: [Input Selection Guide](https://ux-patterns-for-developers-nqu072an6.vercel.app/en/patterns/forms/input-selection-guide) Learn how to select the most appropriate input types for your web forms. Get guidance on when to use text fields, dropdowns, checkboxes, and other form controls. # Input Selection Guide ## When to use Different Types of Text Fields? ```mermaid graph TD A[Do users need to enter freeform text?] -->|Yes| B[Does it require a single line?] B -->|Yes| C[Use Standard Text Field ``] B -->|No| D[Use Textarea `