Sub topic 4
Autocomplete and Query Suggestions
This chapter covers the suggestion dropdown that appears under a search field as the user types. It assumes you have read the chapter on designing the search field. You should be comfortable with HTML forms and basic TypeScript. The ARIA attributes shown here get a fuller treatment in the accessibility chapter.
What suggestions are for
Suggestions help the user finish a query faster, avoid typos, and discover what the system can find. They do not replace the results page. A suggestion is a shortcut to a query or a destination, and the user can ignore it.
Not all suggestions do the same job. Mixing them without labels confuses users.
| Type | What it offers | Example for "boo" | On selection |
|---|---|---|---|
| Query completion | A full query that extends what was typed | "boots waterproof" | Runs a search |
| Query correction | A likely fix for a typo | "Did you mean: boots" | Runs a search |
| Entity suggestion | A specific item, brand, or category | "Boots (category)" | Goes straight to that page |
| Recent search | A query this user ran before | "hiking boots" with a history icon | Runs a search |
| Popular search | A query many users run | "Trending: boot socks" | Runs a search |
Show the type when the destination differs. Query completions run a search, and entity suggestions navigate away. If both look identical, users cannot predict what Enter will do.
Where suggestions come from
Good suggestions usually combine several sources.
- Query logs. Popular past queries, filtered to remove rare, offensive, or personal ones. Apply a minimum count so one user's unusual query never appears for others.
- Catalog data. Product names, brands, and categories, matched by prefix or by word.
- User history. Recent searches, stored per user and easy to remove.
- Context. The current section, location, or language can narrow the candidates.
Matching usually starts with prefix matching on each word, so "hik" matches "waterproof hiking boots". Ranking within the list should favor popularity, then exact-prefix matches, then recency. Keep history in its own labeled group, or at the top when the field is empty and focused. Many apps show recent searches at that moment, before any typing, which saves effort on repeated tasks.
Anatomy of the interaction
The dropdown is a small state machine. Knowing its states helps you handle the edge cases listed later.
Several rules follow from this model.
- Typed text always wins on Enter, unless an option is highlighted. Do not auto-highlight the first suggestion. If the user types "shoes" and presses Enter, they expect a search for "shoes", not for a suggestion that happened to rank first.
- Arrow keys move through options and update a visual highlight. Whether the input text changes to match the highlighted option is a design choice. Updating the text previews the result. Leaving it alone keeps what the user typed.
- Escape closes the list. A second Escape may clear the field.
- Clicking or tapping an option submits immediately. Do not make the user click twice.
- Blur closes the list, but not before a click lands. A common bug is that the input loses focus on mousedown and the list disappears before the click event fires. Select on
mousedown, or prevent the default on the list so focus stays in the input.
Showing the match
Bold the part of the suggestion the user did not type. For "hik", display "hiking boots" with the completion emphasized. This draws the eye to what is new. Some products bold the typed part instead, which works too, but pick one style and use it everywhere.
Keep rows short and scannable. Use at most eight to ten rows on desktop and fewer on small screens, where the keyboard covers much of the viewport. Truncate long entries with an ellipsis, and avoid wrapping to a second line.
Request behavior
Fetching on every keystroke wastes requests and can show stale results. Three techniques work together.
Debounce. Wait until the user pauses, commonly 150 to 250 ms, before sending a request. The snippet below shows a reusable debounce function.
function debounce<A extends unknown[]>(fn: (...args: A) => void, waitMs: number) {
let timer: ReturnType<typeof setTimeout> | undefined;
return (...args: A) => {
if (timer !== undefined) clearTimeout(timer);
timer = setTimeout(() => fn(...args), waitMs);
};
}
const onInput = debounce((value: string) => {
console.log("fetch suggestions for", value);
}, 200);Cancel stale requests. Debouncing reduces requests, but it does not stop a slow response for "bo" from arriving after a fast response for "boots". The late response would overwrite the right list. Abort the previous request when you send a new one.
let controller: AbortController | undefined;
async function fetchSuggestions(value: string): Promise<string[]> {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch(`/api/suggest?q=${encodeURIComponent(value)}`, {
signal: controller.signal,
});
if (!res.ok) return [];
return (await res.json()) as string[];
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") return [];
return [];
}
}Cache. Keep a small in-memory map from prefix to results. When the user backspaces, the earlier list appears instantly.
Also set a minimum length. For most catalogs, start at two characters. One character matches too much to be useful. Skip suggestions for whitespace-only input.
Accessibility of the dropdown
The standard pattern is a combobox. The input has role="combobox", and the list has role="listbox" with role="option" children. Focus stays in the input, and aria-activedescendant points to the highlighted option. Screen reader users also need to know that suggestions exist and how many.
<label for="q">Search products</label>
<input id="q" type="search" role="combobox"
aria-autocomplete="list" aria-expanded="true"
aria-controls="suggest-list" aria-activedescendant="opt-2"
autocomplete="off">
<ul id="suggest-list" role="listbox" aria-label="Suggestions">
<li id="opt-1" role="option">boots</li>
<li id="opt-2" role="option" aria-selected="true">boots waterproof</li>
<li id="opt-3" role="option">boot socks</li>
</ul>
<p role="status">3 suggestions available</p>Set autocomplete="off" so the browser's own history list does not cover yours. Update aria-expanded when the list opens or closes. Update the status text when the count changes, and keep it short so it does not interrupt typing.
Edge cases and common errors
- No matching suggestions. Close the list rather than showing an empty box. The user can still press Enter.
- Slow or failed requests. Never block typing or submitting. If the request fails, close the dropdown silently. Suggestions are an enhancement.
- Input method editors. Users typing Chinese, Japanese, or Korean compose characters before they are final. Do not fetch or change the input during composition. Listen for
compositionstartandcompositionend. - Mobile keyboards. The Enter key should read "Search". Use
type="search"andenterkeyhint="search". - Sensitive history. Let users delete single recent searches and clear all of them. Do not show history on shared kiosks or after sign-out.
- Suggestions that lead to nothing. A suggestion that returns zero results is a broken promise. Filter candidates against the live index, or at least against a recent snapshot.
- Offensive or legally risky completions. Maintain a blocklist and review the top suggestions regularly. Suggestions derived from logs can surface content you would never choose.
- Stale ranking. Popularity data ages. Weight recent queries more, and refresh the suggestion index on a schedule.
Choosing how much to suggest
More is not better. Use these criteria to decide.
| Question | If yes | If no |
|---|---|---|
| Are queries short and predictable, such as product names? | Show query completions | Show fewer, or only corrections |
| Do many users go to the same few destinations? | Add entity suggestions | Keep to query text |
| Do users repeat searches? | Show recent searches on focus | Skip history |
| Is the catalog small, under a few hundred items? | A plain filter-as-you-type list may be enough | Use a dedicated suggestion index |
Measure whether suggestions help. Compare how often users select a suggestion, how long it takes to reach a result, and how often a selected suggestion leads to a result click. The measurement chapter returns to these metrics.
Exercise
A user types "run" and presses Enter. Your dropdown had auto-highlighted the first suggestion, "running shoes women", so the app searched for that instead. What is the design error, and what two changes fix it?
Show answer
The design error is that auto-highlighting makes Enter submit a suggestion the user never chose, so typed text no longer wins. Fix it by (1) not highlighting any option until the user presses an arrow key or hovers, so Enter submits the typed text "run", and (2) setting aria-activedescendant only when an option is actually highlighted, so screen reader users get the same behavior.
Exercise
The user types "bo", then quickly "boots". The list shows results for "bo" afterward. Which two techniques from this chapter prevent this, and why is debouncing alone not enough?
Show answer
Abort the previous request with AbortController when a new one starts, and optionally check that the response matches the current input before rendering. Debouncing only delays the request. A slow response for "bo" can still arrive after the faster response for "boots" and overwrite it.