Integrating keyboard navigation
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 or trackpad.
Autocomplete provides keyboard accessibility out of the box and lets you define how to navigate to results without leaving the keyboard.
The Navigator API defines three navigation schemes based on key combinations:
- In the current tab when hitting
Enter
- In a new tab when hitting
Cmd+Enter
orCtrl+Enter
- In a new window when hitting
Shift+Enter
Usage
To activate keyboard navigation, you need to implement a getItemUrl
function in each of your sources to provide the URL to navigate to. It tells the Navigator API which link to open on Enter
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 leverage their navigate
helper to navigate to internal pages without refreshing the page.
1
2
3
4
5
6
7
8
9
10
11
import { navigate } from 'gatsby';
import { autocomplete } from '@algolia/autocomplete-js';
autocomplete({
// ...
navigator: {
navigate({ itemUrl }) {
navigate(itemUrl);
},
},
});
Reference
Parameter | Description |
---|---|
navigate
|
type: (params: { itemUrl: string, item: TItem, state: AutocompleteState<TItem> }) => void
The function called when a URL should open in the current page. This is triggered on |
navigateNewTab
|
type: (params: { itemUrl: string, item: TItem, state: AutocompleteState<TItem> }) => void
The function called when a URL should open in a new tab. This is triggered on |
navigateNewWindow
|
type: (params: { itemUrl: string, item: TItem, state: AutocompleteState<TItem> }) => void
The function called when a URL should open in a new window. This is triggered on |