Search bar with accessible auto-suggest/autocomplete options

Search Bar with Accessible Auto-suggest/Autocomplete Options #

Description:

Creating an accessible search bar with auto-suggest or autocomplete options allows users to search efficiently, especially on e-commerce or content-heavy sites.

Creating an accessible search bar with auto-suggest or autocomplete options allows users to search efficiently, especially on e-commerce or content-heavy sites.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Accessible Search Bar with Auto-Suggest - Apparel</title>
    <style>
        /* Basic styling for the search bar and suggestions */
        .search-container {
            position: relative;
            width: 300px;
        }
        .suggestions {
            position: absolute;
            top: 100%;
            left: 0;
            width: 100%;
            background-color: #fff;
            border: 1px solid #ccc;
            max-height: 150px;
            overflow-y: auto;
            display: none;
            z-index: 1000;
        }
        .suggestion-item {
            padding: 8px;
            cursor: pointer;
        }
        .suggestion-item:hover, .suggestion-item[aria-selected="true"] {
            background-color: #e0e0e0;
        }
        /* Focus indicator for accessibility */
        .search-input:focus, .suggestion-item:focus {
            outline: 2px solid #005fcc;
        }
    </style>
</head>
<body>
    <div class="search-container">
        <!-- Search input with aria-autocomplete -->
        <label for="search" class="sr-only">Search</label>
        <input type="text" id="search" class="search-input" aria-autocomplete="list" aria-controls="suggestions-list" aria-expanded="false" aria-activedescendant="" role="combobox" placeholder="Search for apparel..." autocomplete="off">
        <!-- Suggestions list with ARIA attributes -->
        <ul id="suggestions-list" class="suggestions" role="listbox" aria-label="Suggested Products"></ul>
    </div>
    <script>
        // Sample data for autocomplete suggestions
        const products = [
            "Men's T-Shirts",
            "Women's Summer Dresses",
            "Men's Jeans",
            "Women's Blouses",
            "Kids' Hoodies",
            "Women's Cardigans",
            "Men's Jackets",
            "Unisex Sneakers",
            "Men's Shorts",
            "Women's Skirts",
            "Kids' Pajamas"
        ];
        const searchInput = document.getElementById('search');
        const suggestionsList = document.getElementById('suggestions-list');
        searchInput.addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase();
            if (query.length === 0) {
                closeSuggestions();
                return;
            }
            const filteredSuggestions = products.filter(product => product.toLowerCase().includes(query));
            displaySuggestions(filteredSuggestions);
        });
        function displaySuggestions(suggestions) {
            suggestionsList.innerHTML = '';
            suggestionsList.style.display = 'none';
            if (suggestions.length > 0) {
                searchInput.setAttribute('aria-expanded', 'true');
                suggestionsList.style.display = 'block';
                suggestions.forEach((suggestion, index) => {
                    const suggestionItem = document.createElement('li');
                    suggestionItem.className = 'suggestion-item';
                    suggestionItem.role = 'option';
                    suggestionItem.tabIndex = -1;
                    suggestionItem.id = `suggestion-${index}`;
                    suggestionItem.setAttribute('aria-selected', 'false');
                    suggestionItem.innerText = suggestion;
                    // Handle click and keyboard navigation
                    suggestionItem.addEventListener('click', () => {
                        searchInput.value = suggestion;
                        closeSuggestions();
                    });
                    suggestionItem.addEventListener('keydown', (e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            searchInput.value = suggestion;
                            closeSuggestions();
                        }
                    });
                    suggestionsList.appendChild(suggestionItem);
                });
            } else {
                searchInput.setAttribute('aria-expanded', 'false');
            }
        }
        // Keyboard navigation for suggestions
        searchInput.addEventListener('keydown', (e) => {
            const activeItem = document.querySelector('.suggestion-item[aria-selected="true"]');
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                if (activeItem) {
                    const nextItem = activeItem.nextElementSibling;
                    if (nextItem) {
                        setActiveDescendant(nextItem);
                    }
                } else if (suggestionsList.firstChild) {
                    setActiveDescendant(suggestionsList.firstChild);
                }
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                if (activeItem) {
                    const prevItem = activeItem.previousElementSibling;
                    if (prevItem) {
                        setActiveDescendant(prevItem);
                    }
                }
            } else if (e.key === 'Escape') {
                closeSuggestions();
            }
        });
        function setActiveDescendant(item) {
            const activeItem = document.querySelector('.suggestion-item[aria-selected="true"]');
            if (activeItem) activeItem.setAttribute('aria-selected', 'false');
            item.setAttribute('aria-selected', 'true');
            searchInput.setAttribute('aria-activedescendant', item.id);
            item.focus();
        }
        function closeSuggestions() {
            suggestionsList.innerHTML = '';
            suggestionsList.style.display = 'none';
            searchInput.setAttribute('aria-expanded', 'false');
            searchInput.removeAttribute('aria-activedescendant');
        }
    </script>
</body>
</html>

Explanation #

  1. ARIA Roles and Attributes:
    • role="combobox" on the input field lets screen readers know this is a combobox (input field with suggestions).
    • aria-autocomplete="list" indicates that suggestions will appear as the user types.
    • aria-controls="suggestions-list" associates the input with the suggestions list.
    • aria-expanded changes dynamically to true when suggestions are shown and false when they are hidden.
    • aria-activedescendant is dynamically set to the ID of the currently highlighted suggestion, providing context for screen readers.
    • role="listbox" on the suggestions container and role="option" on each suggestion item makes it clear that these are selectable options.
  2. Keyboard Navigation:
    • Users can navigate through suggestions with ArrowDown and ArrowUp. The selected item is highlighted with aria-selected="true".
    • Enter or Space selects the highlighted suggestion and populates the input field with the chosen text.
    • Escape closes the suggestions without selecting any text.
  3. Display and Focus Management:
    • Displaying Suggestions: The displaySuggestions function dynamically generates suggestion items based on the input value and attaches appropriate event listeners.
    • Focus Management: setActiveDescendant updates the aria-activedescendant attribute and focuses the selected item.
    • Closing Suggestions: The closeSuggestions function clears and hides suggestions, setting aria-expanded="false".
  4. Accessible Design Features:
    • Visible Focus Indicator: The input and each suggestion item has a clear focus style, enhancing accessibility for keyboard users.
    • ARIA Live Region for Announcements: Each suggestion has aria-live="polite", ensuring that new suggestions are announced without interrupting the user.

Key Takeaways #

  • Use ARIA Attributes to Define Roles and States: aria-autocomplete, aria-expanded, aria-activedescendant, and role attributes help screen readers interpret the search bar’s behavior.
  • Enable Full Keyboard Accessibility: Allow users to open, close, and navigate the suggestions list using standard keyboard controls (e.g., ArrowDown, Enter, Escape).
  • Manage Focus and Active States: Dynamically update aria-selected and aria-activedescendant to keep the currently highlighted suggestion accessible to screen reader users.


Screen reader: NVDA
Video:

What are your feelings

Updated on March 6, 2025