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 #
- 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-expandedchanges dynamically totruewhen suggestions are shown andfalsewhen they are hidden.aria-activedescendantis dynamically set to the ID of the currently highlighted suggestion, providing context for screen readers.role="listbox"on the suggestions container androle="option"on each suggestion item makes it clear that these are selectable options.
- Keyboard Navigation:
- Users can navigate through suggestions with
ArrowDownandArrowUp. The selected item is highlighted witharia-selected="true". EnterorSpaceselects the highlighted suggestion and populates the input field with the chosen text.Escapecloses the suggestions without selecting any text.
- Users can navigate through suggestions with
- Display and Focus Management:
- Displaying Suggestions: The
displaySuggestionsfunction dynamically generates suggestion items based on the input value and attaches appropriate event listeners. - Focus Management:
setActiveDescendantupdates thearia-activedescendantattribute and focuses the selected item. - Closing Suggestions: The
closeSuggestionsfunction clears and hides suggestions, settingaria-expanded="false".
- Displaying Suggestions: The
- 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, androleattributes 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-selectedandaria-activedescendantto keep the currently highlighted suggestion accessible to screen reader users.
Screen reader: NVDA
Video: