Skip to main content
Keyboard navigation is essential to a satisfying autocomplete experience. This is one of the most important aspects of web accessibility: users should be able to interact with an autocomplete without using a mouse. Autocomplete provides keyboard accessibility out of the box and lets you define how to visit results without leaving the keyboard. The Navigator API defines three navigation schemes based on key combinations:
  • In the current tab when pressing Enter
  • In a new tab when pressing Cmd+Enter or Ctrl+Enter
  • In a new window when pressing Shift+Enter

Usage

To activate keyboard navigation, you need to implement a getItemUrl function in each of your sources to provide the target URL. It tells the Navigator API which link to open on Enter.
JavaScript
autocomplete({
  // ...
  getSources() {
    return [
      {
        sourceId: "mySource",
        getItemUrl({ item }) {
          return item.url;
        },
        getItems() {
          return [
            // ...
          ];
        },
      },
    ];
  },
  // Default Navigator API implementation
  navigator: {
    navigate({ itemUrl }) {
      window.location.assign(itemUrl);
    },
    navigateNewTab({ itemUrl }) {
      const windowReference = window.open(itemUrl, "_blank", "noopener");

      if (windowReference) {
        windowReference.focus();
      }
    },
    navigateNewWindow({ itemUrl }) {
      window.open(itemUrl, "_blank", "noopener");
    },
  },
});
By default, the Navigator API uses the Location API (see default implementation in the preceding code example). If you’re relying on native document-based routing, this should work out of the box. If you’re using custom client-side routing, you can use the Navigator API to connect your autocomplete with it. For example, if you’re using Autocomplete in a Gatsby website, you can use their navigate helper to go to internal pages without refreshing the page.
JavaScript
import { navigate } from "gatsby";
import { autocomplete } from "@algolia/autocomplete-js";

autocomplete({
  // ...
  navigator: {
    navigate({ itemUrl }) {
      navigate(itemUrl);
    },
  },
});

Reference

navigate
(params: { itemUrl: string, item: TItem, state: AutocompleteState<TItem> }) => void
The function called when a URL should open in the current page (when pressing Enter).
navigateNewTab
(params: { itemUrl: string, item: TItem, state: AutocompleteState<TItem> }) => void
The function called when a URL should open in a new tab (when pressing Ctrl+Enter or Cmd+Enter).
navigateNewWindow
(params: { itemUrl: string, item: TItem, state: AutocompleteState<TItem> }) => void
The function called when a URL should open in a new window (when pressing Shift+Enter).
I