# Combobox
Extend your autocomplete and command palette using the Combobox, which provides robust keyboard navigation and accessibility out of the box.
# Installation
# Initialize your combobox
Given the following markup:
<div>
<input type="text" />
<ul hidden>
<li role="option">Option 1</li>
<li role="option">Option 2</li>
</ul>
</div>
import Combobox from '@ambiki/combobox';
const input = document.querySelector('input');
const list = document.querySelector('ul');
const combobox = new Combobox(input, list);
If multiple selections are allowed, then set multiple: true
. By default, it's false
.
const combobox = new Combobox(input, list, { multiple: true });
# API
# start
Sets up event listeners and attributes on the elements.
combobox.start();
# stop
Removes event listeners and attributes from the elements.
combobox.stop();
# select
Sets aria-selected="true"
on the option element. If it's a single select, then it deselects all the options and
selects only the provided option.
const option = list.querySelector('li[role="option"]');
combobox.select(option);
# deselect
Sets aria-selected="false"
on the option element.
const option = list.querySelector('li[role="option"]');
combobox.deselect(option);
# deselectAll
Sets aria-selected="false"
on all the option elements.
combobox.deselectAll();
# activate
Sets data-active
attribute on the option element. It also sets aria-activedescendant
as the id
of the option
on the input field.
const option = list.querySelector('li[role="option"]');
combobox.activate(option);
TIP
You can also scroll to the activated option by setting scroll: true
. By default, it's false
.
combobox.activate(option, { scroll: true });
# deactivate
Removes data-active
and aria-activedescendant
attribute from the option and input field respectively.
combobox.deactivate();
# isSelected
Returns true
if the option has aria-selected="true"
, false
otherwise.
const option = list.querySelector('li[role="option"]');
combobox.isSelected(option);
// false
# options
Returns an array of all the option elements within the list.
combobox.options;
# activeOption
Returns the option element that has the data-active
attribute
const option = list.querySelector('li[role="option"]');
combobox.activate(option);
combobox.activeOption;
// option
# initializeOptions
Sets tabindex="-1"
, id
, and aria-selected="false"
on the options.
combobox.initializeOptions();
# Events
Name | Description |
---|---|
combobox:commit | This event is fired after selecting/deselecting an option. The option element will be available as the target property of the event. |