Search boxes that suggest matches as you type ("autocomplete") are everywhere: country pickers, tag inputs, command palettes. Drawing a list under an input is the easy part. A screen reader user also needs to hear that suggestions exist, which one is highlighted, and when the list closes. A keyboard user needs to move through the suggestions without focus ever leaving the input. The WAI-ARIA combobox pattern describes how this works with aria-activedescendant.
Write a function createCombobox(input, listbox, config) that turns a text input and an empty list into an accessible combobox:
<label for="fruit">Fruit</label> <input id="fruit" /> <ul></ul>
config.options is an array of strings. config.onSelect(value) is optional and is called when the user picks one. The function returns an object with a destroy() method.
Roles and relationships
role="combobox", aria-autocomplete="list", aria-expanded="false" and autocomplete="off" (so the browser's own suggestions don't cover yours).role="listbox". If it has no id, give it <input id>-listbox. The input's aria-controls points at the list's id.Open and closed
hidden attribute, the input has aria-expanded="true", and the list contains one <li role="option"> per match.hidden attribute and no children, the input has aria-expanded="false", and the input has no aria-activedescendant.<listbox id>-option-<index>, where index is its position in the shown list, starting at 0. Its text is the matching string, and it has aria-selected="false" unless it is the active option.Typing
On every input event, take the input's value without surrounding spaces:
createCombobox(input, listbox, {
options: ["Apple", "Apricot", "Banana", "Pineapple"],
onSelect: (value) => console.log("picked", value),
});
// user types "ap" -> list shows Apple, Apricot, Pineapple
// user types "zz" -> list closes
Keyboard (all on keydown of the input; focus always stays on the input)
preventDefault(), so the text cursor doesn't jump.aria-selected="true" on it, "false" on the others, and points the input's aria-activedescendant at its id.preventDefault(). With no active option, or a closed list, do nothing.preventDefault() in both cases, and not when it does nothing.Picking an option
Picking an option, with Enter or by clicking it, sets the input's value to that option's text, closes the list, and then calls onSelect(value).
Cleaning up
destroy() closes the list and removes every listener the combobox added.
<label for="fruit">Fruit</label>
<input id="fruit" />
<ul></ul>createCombobox(input, listbox, {
options: ["Apple", "Apricot", "Banana", "Pineapple"],
onSelect: (value) => console.log("picked", value),
});
// user types "ap" -> list shows Apple, Apricot, Pineapple
// user types "zz" -> list closes