Skip to content

Search suggestions

A site's search box that suggests pages as a person types.

<p>Type two letters of a field guide (try "fi" or "mo") to see suggestions; Enter with none chosen searches.</p>
<div class="cap-search-suggest" data-cap="search-suggest">
  <form class="cap-search" role="search" aria-label="Search the library" action="#results">
    <div class="cap-field">
      <label class="cap-field-label" for="q-closed">Search the library</label>
      <div class="cap-input-group">
        <div class="cap-input-addon" data-align="inline-start">
          <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5" /><path d="M10.5 10.5L14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" /></svg>
        </div>
        <input class="cap-input" id="q-closed" name="q" type="search" enterkeyhint="search" placeholder="Title or author" value="" />
        <div class="cap-input-addon" data-align="inline-end">
          <button type="button" class="cap-btn" data-size="xs" data-variant="quiet" data-icon-only data-cap-part="clear" aria-label="Clear search" hidden>
            <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" /></svg>
          </button>
        </div>
      </div>
    </div>
  </form>
</div>

Installation

// package.json: "capsomer": "github:DrDustinEdwards/capsomer#v0.152.2"
import "capsomer/tokens.css";
import "capsomer/base.css";
import "capsomer/search-suggest.css";
import { enhance } from "capsomer/behavior/search-suggest";

enhance();

Usage

import { enhance, attachSuggest } from "capsomer/behavior/search-suggest";
enhance({
  suggest: async (q, signal) => {
    const res = await fetch(`/api/v1/search/suggest?q=${encodeURIComponent(q)}`, { signal });
    const { books } = await res.json();
    return books.map((b) => ({ label: b.title, hint: b.author, href: `/books/${b.slug}` }));
  },
});
import { SearchSuggest } from "capsomer/react/search-suggest";
<SearchSuggest label="Search books and authors" labelHidden action="/search" name="q" placeholder="Search titles and authors" defaultValue={q} suggest={suggestBooks} go={(href) => navigate(href)} search={(q) => navigate(`/search?q=${encodeURIComponent(q)}`)} />

Examples

Label read but not shown

<div class="cap-search-suggest" data-cap="search-suggest">
  <form class="cap-search" role="search" aria-label="Search books and authors" action="#results">
    <div class="cap-field">
      <label class="cap-field-label cap-sr-only" for="q-hidden">Search books and authors</label>
      <div class="cap-input-group">
        <div class="cap-input-addon" data-align="inline-start">
          <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5" /><path d="M10.5 10.5L14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" /></svg>
        </div>
        <input class="cap-input" id="q-hidden" name="q" type="search" enterkeyhint="search" placeholder="Title or author" value="" />
        <div class="cap-input-addon" data-align="inline-end">
          <button type="button" class="cap-btn" data-size="xs" data-variant="quiet" data-icon-only data-cap-part="clear" aria-label="Clear search" hidden>
            <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" /></svg>
          </button>
        </div>
      </div>
    </div>
  </form>
</div>

Open, an option active

<div class="cap-search-suggest">
  <form class="cap-search" role="search" aria-label="Search the archive" action="#results">
    <div class="cap-field">
      <label class="cap-field-label" for="q-open">Search the archive</label>
      <div class="cap-input-group">
        <div class="cap-input-addon" data-align="inline-start">
          <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5" /><path d="M10.5 10.5L14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" /></svg>
        </div>
        <input class="cap-input" id="q-open" name="q" type="search" value="field" role="combobox" aria-autocomplete="list" aria-expanded="true" aria-controls="q-open-list" aria-activedescendant="q-open-list-1" autocomplete="off" />
      </div>
    </div>
  </form>
  <div class="cap-listbox cap-search-suggest-list" data-variant="surface" role="listbox" id="q-open-list" aria-label="Suggestions">
    <div class="cap-option" role="option" id="q-open-list-0" data-href="#field-notes"><span class="cap-option-label">Field Notes on Moss</span><span class="cap-option-keys"><span class="cap-option-hint">Ada Marsh</span></span></div>
    <div class="cap-option" role="option" id="q-open-list-1" data-active data-href="#field-guide"><span class="cap-option-label">A Field Guide to Ferns</span><span class="cap-option-keys"><span class="cap-option-hint">Rowan Hale</span></span></div>
    <div class="cap-option" role="option" id="q-open-list-2" data-href="#fieldwork"><span class="cap-option-label">Fieldwork in the Long Valley, a Survey of Three Summers</span><span class="cap-option-keys"><span class="cap-option-hint">Imre Toth</span></span></div>
  </div>
</div>

API reference

SearchSuggest

PropTypeRequiredDoes
defaultValuestringThe text the box opens with (the query a results page shows). Suggestions start only once the person types.
labelReactNodeYes
helpReactNodeHelp, shown between the label and the control and read as its description.
labelHiddenbooleanThe label is read but not shown, for a field whose purpose the page already makes plain (a site's search box with its icon). Every other field shows its label.
landmarkstring
search(query: string) => voidRuns the search in place of the form's own submit (a router's navigate to the results). The form submits as it is by default.
go(href: string) => voidGoes to a picked suggestion. A full page load by default; a router passes its navigate.
suggest(query: string, signal: AbortSignal) => Promise<Suggestion[]>YesAsks for the suggestions for what was typed. A newer keystroke aborts the older request through signal, so an answer never lands out of order. A failed request suggests nothing: the form still searches.
delaynumberWaits this long after the last key before asking (180 ms), and asks nothing below min characters (2).
actionstringYesWhere the search runs with no script, and the form's GET target: "/search".
rootClassNamestringA class of the site's own on the root, for its tokens (a taller box).

And every attribute of <input>.

Functions

FunctionSignatureDoes
suggestionsText(count: number): string
suggestionOption(s: Suggestion, id: string): HTMLElementDraws one suggestion as an option: its label, then its hint at the end.
attachSuggest(root: HTMLElement, opts: SuggestOptions): () => voidWires one .cap-search-suggest around a search field. The list is the root's own [role="listbox"], or one made at its end. Returns a function that detaches.
enhance(opts: SuggestOptions, root?: ParentNode): () => voidAttaches to every [data-cap="search-suggest"] under root not yet ready.

Parts and data attributes

ClassIs
.cap-search-suggestthe root
.cap-search-suggest-lista part

Accessibility

KeyDoes
TypingAsks for suggestions after two letters
ArrowDownOpens the list again; then moves the active option down
ArrowUpMoves the active option up
EnterGoes to the active suggestion; with none active, searches
EscCloses the list; once closed, clears the box
TabLeaves the box; the list closes
  • The landmark is a search form named by its label; the label is shown, or read and not shown with labelHidden where the page already makes the box plain (a hero's search with its icon).
  • Options are named by their label then their hint: "A Field Guide to Ferns Rowan Hale".
  • A long title wraps in the list, never cut (WCAG 1.4.12).
  • Forced colors: the list's edge is CanvasText; the active option keeps the listbox's outline.