Build an Autocomplete Search Box in Vanilla JavaScript
Build an autocomplete search box in vanilla JavaScript with a debounced fetch, abortable requests, keyboard navigation and the ARIA combobox pattern.

An autocomplete box looks simple and hides a lot of ways to go wrong. Requests fire on every keystroke and arrive out of order, so an old answer overwrites a newer one. The suggestion list captures the mouse but not the keyboard. A screen reader hears nothing at all, because nothing tells it that a list of options has appeared. This post builds an autocomplete search box in vanilla JavaScript that handles each of those problems: a debounced input, a request that is cancelled when a newer one starts, a result list you can navigate with the arrow keys, highlighting of the matching text and the ARIA combobox pattern that makes it work with assistive technology. The same structure works against any search endpoint. The pattern follows the WAI-ARIA combobox guidance, and the request code uses fetch and AbortController, documented on MDN.
The markup
The input is a combobox, and the list it controls is a listbox. The ARIA attributes declare that relationship, and a live region announces how many results there are.
<div class="search">
<label for="q">Search countries</label>
<input
id="q"
type="text"
role="combobox"
autocomplete="off"
aria-autocomplete="list"
aria-expanded="false"
aria-controls="results"
aria-activedescendant="">
<ul id="results" role="listbox" hidden></ul>
<p id="status" class="visually-hidden" role="status"></p>
</div>
<script type="module" src="search.js"></script>.search { position: relative; max-width: 24rem; }
#q { width: 100%; padding: 0.5rem; box-sizing: border-box; }
#results { position: absolute; inset-inline: 0; margin: 0; padding: 0; list-style: none; background: Canvas; border: 1px solid; max-height: 16rem; overflow: auto; }
#results li { padding: 0.4rem 0.6rem; cursor: pointer; }
#results li[aria-selected="true"] { background: Highlight; color: HighlightText; }
mark { background: transparent; font-weight: 700; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }(a labeled text box with a dropdown list that appears below it)autocomplete="off" turns off the browser's own suggestions, which would otherwise draw over yours. The aria-activedescendant attribute points to the id of the currently highlighted option, so focus can stay in the input while the screen reader announces the option. This is the key idea of the pattern: the user keeps typing, and the highlight is virtual.
A data source
For the example, search a list in memory. In a real app, this function would call your server, and everything else stays the same.
const COUNTRIES = ["Argentina", "Armenia", "Australia", "Austria", "Brazil", "Bulgaria", "Canada", "Chile", "China", "Croatia"];
export async function search(query, { signal } = {}) {
await new Promise((resolve, reject) => {
const timer = setTimeout(resolve, 150);
signal?.addEventListener("abort", () => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
});
});
const q = query.trim().toLowerCase();
return COUNTRIES.filter((name) => name.toLowerCase().includes(q)).slice(0, 8);
}
console.log(await search("ar"));[ 'Argentina', 'Armenia', 'Bulgaria' ]The simulated delay and the abort handling copy what a real fetch does, so the rest of the code is honest about timing. The filter is a substring match, so "ar" also finds Bulgaria. With a real endpoint you would write fetch(url, { signal }) and parse the JSON.
Debounce the input
Searching on every keystroke wastes requests while the person is still typing. A debounce waits until typing pauses for a short time, usually 150 to 300 milliseconds, before acting.
export function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
const log = debounce((text) => console.log("search:", text), 200);
log("a");
log("ar");
log("arm");search: armOnly the last call runs, 200 milliseconds after the last keystroke. A debounce reduces how many requests start, but it does not make responses arrive in order, which is the next problem.
Cancel stale requests
If a request for "ar" is slow and a request for "arm" returns first, the old answer arriving later would replace the correct list. The fix is to abort the previous request whenever a new one starts.
import { search } from "./source.js";
import { debounce } from "./debounce.js";
const input = document.querySelector("#q");
const list = document.querySelector("#results");
const status = document.querySelector("#status");
let controller = null;
let items = [];
let active = -1;
async function run(query) {
controller?.abort();
if (query.trim().length < 2) {
close();
return;
}
controller = new AbortController();
try {
items = await search(query, { signal: controller.signal });
renderList(query);
} catch (error) {
if (error.name !== "AbortError") throw error;
}
}
input.addEventListener("input", debounce(() => run(input.value), 200));(typing "arm" cancels the earlier request for "ar" so only the newest list is shown)Requiring two characters avoids a pointless search on a single letter. The AbortError is expected, so it is swallowed, and any other error is rethrown so it is not hidden.
Render with highlights
Rendering builds one list item per result. Highlight the matched part with a <mark> element, built with the DOM instead of strings, so a result containing angle brackets cannot inject markup.
function renderList(query) {
list.replaceChildren();
active = -1;
input.setAttribute("aria-activedescendant", "");
items.forEach((name, index) => {
const li = document.createElement("li");
li.id = `option-${index}`;
li.setAttribute("role", "option");
li.setAttribute("aria-selected", "false");
const start = name.toLowerCase().indexOf(query.trim().toLowerCase());
if (start === -1) {
li.textContent = name;
} else {
const end = start + query.trim().length;
const mark = document.createElement("mark");
mark.textContent = name.slice(start, end);
li.append(name.slice(0, start), mark, name.slice(end));
}
list.append(li);
});
const open = items.length > 0;
list.hidden = !open;
input.setAttribute("aria-expanded", String(open));
status.textContent = open ? `${items.length} suggestions available` : "No suggestions";
}
function close() {
items = [];
active = -1;
list.hidden = true;
input.setAttribute("aria-expanded", "false");
input.setAttribute("aria-activedescendant", "");
}(typing "arm" shows "Armenia" with "Arm" in bold and announces "1 suggestions available")The live region announces the number of results, which is the equivalent of the visual list appearing. If you want correct grammar for one result, choose the sentence by count.
Keyboard navigation
The arrow keys move the virtual highlight, Enter selects it and Escape closes the list. Because the real focus never leaves the input, these keys are handled on the input.
function setActive(index) {
const options = [...list.children];
options.forEach((li, i) => li.setAttribute("aria-selected", String(i === index)));
active = index;
input.setAttribute("aria-activedescendant", index >= 0 ? options[index].id : "");
options[index]?.scrollIntoView({ block: "nearest" });
}
function choose(index) {
if (index < 0) return;
input.value = items[index];
close();
}
input.addEventListener("keydown", (event) => {
if (list.hidden) return;
if (event.key === "ArrowDown") {
event.preventDefault();
setActive((active + 1) % items.length);
} else if (event.key === "ArrowUp") {
event.preventDefault();
setActive((active - 1 + items.length) % items.length);
} else if (event.key === "Enter" && active >= 0) {
event.preventDefault();
choose(active);
} else if (event.key === "Escape") {
close();
}
});
list.addEventListener("mousedown", (event) => {
const li = event.target.closest("li");
if (!li) return;
event.preventDefault();
choose([...list.children].indexOf(li));
});
document.addEventListener("click", (event) => {
if (!event.target.closest(".search")) close();
});(Down Arrow highlights the first suggestion, Enter fills the input and closes the list)The modulo arithmetic wraps the highlight from the last option to the first. Using mousedown with preventDefault() on the list prevents the input from losing focus before the click registers, which would otherwise close the list and swallow the selection. Clicking anywhere outside the widget closes the list.
Practical notes
Cache results by query in a Map, so retyping a term does not trigger another request. Handle slow or failing requests by showing a status message rather than leaving the box blank, and consider a loading indicator after a few hundred milliseconds. Do not trust the data you display: a server result is still text you insert with textContent. Rank matches with prefix matches first, since people expect "arm" to show Armenia before Bulgaria's substring match. On mobile, check that the on-screen keyboard does not cover the list, and set enterkeyhint="search" on the input if pressing Enter submits a search.
Handling real-world problems
The version above is a good start, and a production search box meets a few more problems. Network errors need a visible state: if a request fails, keep the previous results if there are any, show a short message such as "Suggestions are unavailable" in the live region and let the user press Enter to run a normal search. Never leave the box in a silent broken state, because the person will assume nothing matches.
Caching saves time. Keep a Map from the normalized query to its results, and consult it before starting a request, so deleting a character and typing it again is instant. Limit the cache size, because a long session can fill it, and drop the oldest entries with a simple cap.
Input methods matter more than most developers expect. People typing in Chinese, Japanese or Korean compose text in several steps, and the input event fires during composition. Listen for compositionstart and compositionend, and skip searching while composition is active, or the list will flicker on half-formed characters. Also trim and normalize accents if your data requires it, for example with String.prototype.normalize("NFD") and removing the combining marks, so "cafe" finds "café".
Last, decide what Enter does when nothing is highlighted. The usual answer is to submit the text as a normal search, which the browser does by default if the input is inside a form, so keep the widget inside a form and only intercept Enter when an option is highlighted.
Testing the search box
Test the logic that is easy to get wrong. Type quickly and confirm only one request runs per pause. Throttle the network, type a term, then change it before the first response arrives, and confirm that the older response never appears. Use only the keyboard: type, press Down, press Up at the top to wrap, press Enter to choose and press Escape to close. With a screen reader running, check that it announces the number of suggestions when the list opens and the highlighted option as you move. Finally, try an empty result, a request that fails and a term containing characters such as an ampersand and a less-than sign, which must be displayed as text.


