Reading history

JavaScript Project: Search Autocomplete

9 min read 0 views

Build a search autocomplete in JavaScript with debouncing, AbortController, safe highlighting, keyboard support and ARIA roles.

Search boxes that suggest results as you type are everywhere: maps, shops and course sites. In this project you will build one that searches Bangladesh’s districts. It looks simple, but it solves several real problems. It waits until typing pauses, cancels old searches that are no longer needed and highlights the matching letters safely. Users can pick a result with the keyboard, and screen readers are told what is happening. It brings together skills from many earlier lessons.

In this project you will

  • Debounce input so searches run only when typing pauses
  • Cancel out-of-date searches with AbortController
  • Highlight matches by building DOM nodes, not HTML strings
  • Add arrow-key, Enter and Escape support
  • Announce the choice with a custom event, plus ARIA roles for accessibility

You should know async/await, AbortController, keyboard events and custom events.

The Finished App

Result

Try typing “sy”, “kh” or “ganj”. Use the arrow keys and Enter to choose, or click a result.

The Complete Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>District search with autocomplete</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; font-size: 15px; }
    .combo { position: relative; max-width: 340px; }
    label { display: block; font-weight: 600; margin-bottom: 4px; }
    input { width: 100%; box-sizing: border-box; padding: 8px 10px; font: inherit; border: 2px solid #90a4ae; border-radius: 8px; }
    input:focus { outline: none; border-color: #1e88e5; }
    ul { list-style: none; margin: 4px 0 0; padding: 4px; border: 1px solid #ccc; border-radius: 8px;
         background: white; position: absolute; inset-inline: 0; box-shadow: 0 4px 12px #0002; }
    ul[hidden] { display: none; }
    li { padding: 6px 8px; border-radius: 6px; cursor: pointer; display: flex; justify-content: space-between; }
    li[aria-selected="true"] { background: #e3f2fd; }
    li small { color: #78909c; }
    mark { background: #fff59d; padding: 0; }
    #status { color: #607d8b; font-size: 13px; min-height: 1.3em; margin-top: 6px; }
    #chosen { margin-top: 130px; }
  </style>
</head>
<body>
  <div class="combo">
    <label for="q">Search a district</label>
    <input id="q" role="combobox" aria-expanded="false" aria-controls="list"
           aria-autocomplete="list" autocomplete="off" placeholder="e.g. sy, pur, kh">
    <ul id="list" role="listbox" hidden></ul>
    <div id="status" aria-live="polite"></div>
  </div>
  <p id="chosen">No district chosen yet.</p>

  <script>
    const DISTRICTS = [
      ["Dhaka", "Dhaka"], ["Gazipur", "Dhaka"], ["Narayanganj", "Dhaka"], ["Tangail", "Dhaka"],
      ["Faridpur", "Dhaka"], ["Chattogram", "Chattogram"], ["Cox's Bazar", "Chattogram"],
      ["Cumilla", "Chattogram"], ["Feni", "Chattogram"], ["Noakhali", "Chattogram"],
      ["Rajshahi", "Rajshahi"], ["Bogura", "Rajshahi"], ["Pabna", "Rajshahi"], ["Naogaon", "Rajshahi"],
      ["Khulna", "Khulna"], ["Jashore", "Khulna"], ["Kushtia", "Khulna"], ["Satkhira", "Khulna"],
      ["Barishal", "Barishal"], ["Patuakhali", "Barishal"], ["Bhola", "Barishal"],
      ["Sylhet", "Sylhet"], ["Moulvibazar", "Sylhet"], ["Sunamganj", "Sylhet"], ["Habiganj", "Sylhet"],
      ["Rangpur", "Rangpur"], ["Dinajpur", "Rangpur"], ["Kurigram", "Rangpur"],
      ["Mymensingh", "Mymensingh"], ["Jamalpur", "Mymensingh"], ["Sherpur", "Mymensingh"]
    ].map(([name, division]) => ({ name, division }));

    // 1. A fake server search that takes time and can be cancelled
    function searchDistricts(text, signal) {
      return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
          const t = text.toLowerCase();
          resolve(DISTRICTS.filter(d => d.name.toLowerCase().includes(t)).slice(0, 6));
        }, 150 + Math.random() * 200);
        signal.addEventListener("abort", () => {
          clearTimeout(timer);
          reject(new DOMException("Search cancelled", "AbortError"));
        });
      });
    }

    // 2. Debounce: wait until typing pauses before searching
    const debounce = (fn, ms) => {
      let id;
      return (...args) => { clearTimeout(id); id = setTimeout(() => fn(...args), ms); };
    };

    const input = document.getElementById("q");
    const list = document.getElementById("list");
    const status = document.getElementById("status");
    let results = [], active = -1, controller = null;

    // 3. Build "Sy<mark>lh</mark>et" with DOM nodes, never with innerHTML
    function highlighted(name, text) {
      const frag = document.createDocumentFragment();
      const i = name.toLowerCase().indexOf(text.toLowerCase());
      const mark = document.createElement("mark");
      mark.textContent = name.slice(i, i + text.length);
      frag.append(name.slice(0, i), mark, name.slice(i + text.length));
      return frag;
    }

    function render(text) {
      list.replaceChildren();
      results.forEach((d, i) => {
        const li = document.createElement("li");
        li.id = "opt-" + i;
        li.setAttribute("role", "option");
        li.setAttribute("aria-selected", i === active);
        const span = document.createElement("span");
        span.append(highlighted(d.name, text));
        const small = document.createElement("small");
        small.textContent = d.division;
        li.append(span, small);
        li.addEventListener("mousedown", e => { e.preventDefault(); choose(i); });
        list.append(li);
      });
      const open = results.length > 0;
      list.hidden = !open;
      input.setAttribute("aria-expanded", open);
      input.setAttribute("aria-activedescendant", active >= 0 ? "opt-" + active : "");
    }

    const runSearch = debounce(async text => {
      controller?.abort();                 // cancel the previous, slower search
      if (text.length < 2) { results = []; render(text); status.textContent = ""; return; }
      controller = new AbortController();
      status.textContent = "Searching…";
      try {
        results = await searchDistricts(text, controller.signal);
        active = -1;
        render(text);
        status.textContent = results.length ? `${results.length} match(es)` : "No district found";
      } catch (err) {
        if (err.name !== "AbortError") throw err;   // cancelled searches are expected
      }
    }, 250);

    input.addEventListener("input", () => runSearch(input.value.trim()));

    // 4. Keyboard support: arrows move, Enter picks, Escape closes
    input.addEventListener("keydown", e => {
      if (list.hidden) return;
      if (e.key === "ArrowDown") active = (active + 1) % results.length;
      else if (e.key === "ArrowUp") active = (active - 1 + results.length) % results.length;
      else if (e.key === "Enter" && active >= 0) { e.preventDefault(); choose(active); return; }
      else if (e.key === "Escape") { results = []; }
      else return;
      e.preventDefault();
      render(input.value.trim());
    });

    // 5. Announce the choice with a custom event, so other code can react
    function choose(i) {
      const d = results[i];
      input.value = d.name;
      results = [];
      render("");
      input.dispatchEvent(new CustomEvent("district-select", { bubbles: true, detail: d }));
    }
    document.addEventListener("district-select", e => {
      document.getElementById("chosen").textContent =
        `You chose ${e.detail.name} (${e.detail.division} Division).`;
    });

    // Start with a sample search so the demo shows results straight away
    input.value = "pur";
    runSearch("pur");
  </script>
</body>
</html>

How It Works

  • Fake server: searchDistricts returns a promise that resolves after a random delay of 150 to 350 ms, like a real network request. It listens for the signal’s abort event, clears its timer and rejects with an AbortError. A real app would call fetch(url, { signal }) instead.
  • Debounce: each key press restarts a 250 ms timer, so typing “sylhet” quickly causes one search, not six.
  • Cancelling: controller?.abort() cancels the previous search before starting a new one. Because response times vary, an old, slow answer could otherwise arrive after a newer one and show the wrong list.
  • Expected errors: the catch ignores AbortError, because a cancelled search is normal. Any other error is re-thrown so it is not hidden.
  • Safe highlighting: highlighted splits the name into three parts and wraps the match in a <mark> created with createElement. Text is added with textContent and append, so data can never inject HTML.
  • Rendering: render rebuilds the list from the results array and the active index each time. The list is a picture of the current state, as in the Kanban board project.
  • Keyboard: the arrow keys change active with wrap-around, Enter chooses and Escape closes. preventDefault() stops the cursor jumping inside the input.
  • Mouse: results use mousedown with preventDefault() rather than click, so the input keeps focus.
  • Accessibility: role="combobox", role="listbox" and role="option" tell screen readers what the parts are. aria-expanded and aria-activedescendant report whether the list is open and which option is active. The status line uses aria-live to announce the number of matches.
  • Custom event: choose dispatches a bubbling district-select event with the district in detail. The paragraph below the box listens for it, so other features could react without changing the search code.

Ideas to Extend the Project

  • Match from the start of names first, then names that contain the text elsewhere.
  • Cache results in a Map so repeating a search needs no request.
  • Remember recent choices in localStorage and show them when the box is empty.
  • Allow searching by division, such as “Sylhet Division”.
  • Add Bangla names and let users search in either language.

Common Mistakes

  1. Not cancelling old requests, so slow responses overwrite newer results.
  2. Building the list with innerHTML and user data, which allows HTML injection.
  3. Using click on results, which can fire after the input loses focus and the list closes.
  4. Searching on every key press without debouncing, which floods the server.

Practice Exercises

Exercise 1. Close the list when the input loses focus.

Show answer
input.addEventListener("blur", () => {
  results = [];
  render("");
});

This works with the results’ mousedown handler, because that handler calls preventDefault() and the input never loses focus when an option is clicked.

Exercise 2. Add a cache so the same search text is never sent twice.

Show answer
const cache = new Map();
async function cachedSearch(text, signal) {
  const key = text.toLowerCase();
  if (!cache.has(key)) cache.set(key, await searchDistricts(text, signal));
  return cache.get(key);
}
// In runSearch, call cachedSearch instead of searchDistricts

Frequently Asked Questions

Could I use the HTML datalist element instead?

Yes, for simple cases. <input list="..."> with a <datalist> gives basic suggestions with no JavaScript. It cannot show extra details such as the division, highlight matches or load results from a server as you type, and it looks different in every browser.

How long should the debounce delay be?

Between 200 and 400 milliseconds feels responsive for most users. Shorter delays send more requests; longer ones make the box feel slow. If the data is already in the browser, you can search on every key press without debouncing.

Summary

  • Debouncing and cancelling with AbortController keep searches efficient and results correct.
  • Build highlighted text with DOM nodes to stay safe from injected HTML.
  • Keyboard handling and ARIA roles make the widget usable for everyone.
  • A custom event lets the rest of the page react to the user’s choice.

Back to the start of the series: JavaScript Introduction.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *