Skip to content

Listbox ​

A list of options to pick one or several from, with keyboard navigation, typeahead and form values.

Installation ​

bash
npx bootcn add listbox
bash
pnpm dlx bootcn add listbox
bash
yarn dlx bootcn add listbox
bash
bunx --bun bootcn add listbox

The CLI also installs the design tokens and these components: label. It prints the <link> and <script> tags to add to your layout.

Usage ​

Use a listbox when the options should stay visible (settings, a short list of choices with descriptions). For a long list, or one to search, use the Combobox; for a simple dropdown, the native Select.

JavaScript API ​

  • A focusable role="listbox" with data-bootcn-listbox, labelled by a visible label; aria-multiselectable="true" for several choices.
  • Options: role="option", an id, data-value and aria-selected.
  • data-bootcn-listbox-name creates hidden inputs for forms (name or name[]).
  • Event bootcn:listbox:change (bubbles), detail.value (array).
  • Bootcn.listbox.init(root) / destroy().

Accessibility ​

  • WAI-ARIA listbox: one tab stop; Up/Down, Home/End and first-letter typeahead move the active option (aria-activedescendant); Space or Enter selects (toggles in multiple mode).
  • Selected options have aria-selected="true" and a check mark.

Dependencies ​

  • Bootstrap 5.3+ CSS.
  • themes/tokens/tokens.css.
  • The label component.

Source ​

The exact files the CLI installs (listbox@1.0.0). View on GitHub · Report an issue

html
<p class="bootcn-label" id="bootcn-listbox-sound-label">Notification sound</p>
<ul
  class="bootcn-listbox mt-2"
  role="listbox"
  tabindex="0"
  aria-labelledby="bootcn-listbox-sound-label"
  data-bootcn-listbox
  data-bootcn-listbox-name="sound"
>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-none"
    data-value="none"
    aria-selected="false"
  >
    <span class="bootcn-listbox__text">
      <span>None</span>
    </span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-chime"
    data-value="chime"
    aria-selected="true"
  >
    <span class="bootcn-listbox__text">
      <span>Chime</span>
      <span class="bootcn-listbox__description">Two soft notes</span>
    </span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-bell"
    data-value="bell"
    aria-selected="false"
  >
    <span class="bootcn-listbox__text">
      <span>Bell</span>
      <span class="bootcn-listbox__description">A single ring</span>
    </span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-pulse"
    data-value="pulse"
    aria-selected="false"
  >
    <span class="bootcn-listbox__text">
      <span>Pulse</span>
      <span class="bootcn-listbox__description">Three short beeps</span>
    </span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-wave"
    data-value="wave"
    aria-selected="false"
  >
    <span class="bootcn-listbox__text">
      <span>Wave</span>
      <span class="bootcn-listbox__description">A rising tone</span>
    </span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
</ul>

<p class="bootcn-label mt-4" id="bootcn-listbox-days-label">Working days</p>
<ul
  class="bootcn-listbox mt-2"
  role="listbox"
  tabindex="0"
  aria-labelledby="bootcn-listbox-days-label"
  aria-multiselectable="true"
  data-bootcn-listbox
  data-bootcn-listbox-name="days"
>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-day-mon"
    data-value="mon"
    aria-selected="true"
  >
    <span class="bootcn-listbox__text">Monday</span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-day-tue"
    data-value="tue"
    aria-selected="true"
  >
    <span class="bootcn-listbox__text">Tuesday</span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-day-wed"
    data-value="wed"
    aria-selected="false"
  >
    <span class="bootcn-listbox__text">Wednesday</span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-day-thu"
    data-value="thu"
    aria-selected="true"
  >
    <span class="bootcn-listbox__text">Thursday</span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
  <li
    class="bootcn-listbox__option"
    role="option"
    id="bootcn-listbox-day-fri"
    data-value="fri"
    aria-selected="false"
  >
    <span class="bootcn-listbox__text">Friday</span>
    <svg
      class="bootcn-icon bootcn-listbox__check"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  </li>
</ul>
css
.bootcn-listbox {
  max-width: 18rem;
  margin: 0;
  padding: 0.25rem;
  border: var(--bootcn-border-width) solid var(--bootcn-border-color);
  border-radius: var(--bootcn-radius-lg);
  background-color: var(--bootcn-background);
  font-size: 0.875rem;
  list-style: none;
}

.bootcn-listbox:focus-visible {
  outline: 0;
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-listbox__option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
  padding: 0.375rem 0.5rem;
  border-radius: var(--bootcn-radius-sm);
  cursor: pointer;
}

.bootcn-listbox__option:hover,
.bootcn-listbox__option.is-active {
  background-color: var(--bootcn-accent);
  color: var(--bootcn-accent-foreground);
}

.bootcn-listbox:focus-visible .bootcn-listbox__option.is-active {
  box-shadow: inset 0 0 0 2px var(--bootcn-ring);
}

.bootcn-listbox__text {
  display: flex;
  flex-direction: column;
}

.bootcn-listbox__description {
  color: var(--bootcn-muted-foreground);
  font-size: 0.75rem;
}

.bootcn-listbox__check {
  flex: none;
  visibility: hidden;
}

.bootcn-listbox__option[aria-selected='true'] .bootcn-listbox__check {
  visibility: visible;
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.listbox) return; // already loaded: idempotent

  const ROOT = '[role="listbox"][data-bootcn-listbox]';
  let listening = false;

  const options = (box) => Array.from(box.querySelectorAll('[role="option"]'));
  const multiple = (box) => box.getAttribute('aria-multiselectable') === 'true';

  function setActive(box, option) {
    options(box).forEach((o) => o.classList.toggle('is-active', o === option));
    if (option) {
      box.setAttribute('aria-activedescendant', option.id);
      option.scrollIntoView({ block: 'nearest' });
    }
  }

  function active(box) {
    return document.getElementById(box.getAttribute('aria-activedescendant')) || null;
  }

  function syncInputs(box) {
    const name = box.getAttribute('data-bootcn-listbox-name');
    if (!name) return;
    let holder = box.nextElementSibling;
    if (!holder || !holder.hasAttribute('data-bootcn-listbox-values')) {
      holder = document.createElement('div');
      holder.hidden = true;
      holder.setAttribute('data-bootcn-listbox-values', '');
      box.after(holder);
    }
    holder.textContent = '';
    options(box)
      .filter((o) => o.getAttribute('aria-selected') === 'true')
      .forEach((o) => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = multiple(box) ? name + '[]' : name;
        input.value = o.getAttribute('data-value') || o.textContent.trim();
        holder.appendChild(input);
      });
  }

  function choose(box, option) {
    if (multiple(box)) {
      option.setAttribute('aria-selected', String(option.getAttribute('aria-selected') !== 'true'));
    } else {
      options(box).forEach((o) => o.setAttribute('aria-selected', String(o === option)));
    }
    syncInputs(box);
    box.dispatchEvent(
      new CustomEvent('bootcn:listbox:change', {
        bubbles: true,
        detail: {
          value: options(box)
            .filter((o) => o.getAttribute('aria-selected') === 'true')
            .map((o) => o.getAttribute('data-value')),
        },
      }),
    );
  }

  function onKeydown(event) {
    const box = event.target.closest && event.target.closest(ROOT);
    if (!box || event.target !== box) return;
    const list = options(box);
    const index = list.indexOf(active(box));
    let next = null;
    if (event.key === 'ArrowDown') next = list[Math.min(list.length - 1, index + 1)];
    else if (event.key === 'ArrowUp') next = list[Math.max(0, index - 1)];
    else if (event.key === 'Home') next = list[0];
    else if (event.key === 'End') next = list[list.length - 1];
    else if (event.key === ' ' || event.key === 'Enter') {
      if (index >= 0) {
        event.preventDefault();
        choose(box, list[index]);
      }
      return;
    } else if (event.key.length === 1 && /\S/.test(event.key)) {
      const key = event.key.toLowerCase();
      const rotated = list.slice(index + 1).concat(list.slice(0, index + 1));
      next = rotated.find((o) => o.textContent.trim().toLowerCase().startsWith(key)) || null;
    }
    if (!next) return;
    event.preventDefault();
    setActive(box, next);
  }

  function onClick(event) {
    const option = event.target.closest && event.target.closest(ROOT + ' [role="option"]');
    if (!option) return;
    const box = option.closest(ROOT);
    box.focus();
    setActive(box, option);
    choose(box, option);
  }

  // On focus, start on the (first) selected option.
  function onFocus(event) {
    const box = event.target;
    if (!(box instanceof Element) || !box.matches(ROOT) || active(box)) return;
    const list = options(box);
    setActive(box, list.find((o) => o.getAttribute('aria-selected') === 'true') || list[0]);
  }

  function init(root = document) {
    root.querySelectorAll(ROOT).forEach(syncInputs);
    if (listening) return;
    document.addEventListener('keydown', onKeydown);
    document.addEventListener('click', onClick);
    document.addEventListener('focusin', onFocus);
    listening = true;
  }

  function destroy() {
    if (!listening) return;
    document.removeEventListener('keydown', onKeydown);
    document.removeEventListener('click', onClick);
    document.removeEventListener('focusin', onFocus);
    listening = false;
  }

  ns.listbox = { init: init, destroy: destroy };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => init());
  } else {
    init();
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.