bootstrap icon indicating copy to clipboard operation
bootstrap copied to clipboard

Support searchable accordions via hidden=until-found

Open reteps opened this issue 9 months ago • 0 comments

Prerequisites

Proposal

Add support for searching text within an accordion, using the hidden=until-found property. It will have support in both Firefox and Chrome starting May 27th. This is a big deal for accessibility, as it can prevent certain users from finding the content they need.

Motivation and context

  • Currently, I have to select between an unstyled details element with the ability to search (control+f) collapsed content, and a styled accordion element without the ability to search it's content. Bootstrap should support this out of the box.

I use the following workaround to support a searchable bootstrap accordion:

/* Modified from https://codepen.io/wdzajicek/pen/VYZawjX */

[hidden='until-found'].collapse:not(.show) {
  /* Prevent Bootstrap .collapse class from adding display: none so that beforematch event still fires */
  display: block !important;
}

[hidden='until-found'] {
  display: none !important;
}
const enableAccordionFind = () => {
  // Check browser support for the "beforematch" event
  // (only supported in Chrome and Firefox as of May 2025)
  if (!('onbeforematch' in document.body)) {
    return;
  }
  const accordions = [...document.querySelectorAll('.accordion-collapse.collapse')];
  accordions.forEach((item) => {
    item.hidden = 'until-found';
    const collapse = new bootstrap.Collapse(item, { toggle: false });
    // Manually toggle if a match is found
    item.onbeforematch = (_e) => collapse.toggle();

    item.addEventListener('show.bs.collapse', (_e) => {
      item.removeAttribute('hidden');
    });

    item.addEventListener('hidden.bs.collapse', (_e) => {
      item.hidden = 'until-found';
    });
  });
};

document.addEventListener('DOMContentLoaded', enableAccordionFind);

I'm hoping that this functionality can be added natively to bootstrap.

reteps avatar May 20 '25 17:05 reteps