Building a Bootstrap Dropdown with the details HTML disclosure element

Posted on
Contents

Following on from building a Bootstrap accordion using the details HTML tag, I thought I’d try to build a Bootstrap dropdown using the same details HTML tag.

HTML

<details class="dropdown mb-5">
  <summary class="btn btn-primary dropdown-toggle">
    Open dropdown
  </summary>
  <div>
    <ul class="dropdown-menu" style="display: revert;">
      <li><a class="dropdown-item" href="#">Action</a></li>
      <li><a class="dropdown-item" href="#">Another action</a></li>
      <li><a class="dropdown-item" href="#">Something else here</a></li>
    </ul>
  </div>
</details>

Overall it was easy and quick to get together but it unfortunately brings with it a few minor usability issues.

Unlike a standard Bootstrap downdown component, clicking outside of the dropdown won’t collapse the dropdown and the Esc key won’t collapse it either. Having said that, a standard details/summary element won’t do either of those anyway and the collapse dropdown can still be controlled with a keyboard using the Enter or Space key.

JavaScript (Optional)

You could add a tiny script to close the menu when the Esc key is pressed:

<script>
  document.addEventListener('keydown', function(event) {
  if (event.key === 'Escape') {
    let detailsElements = document.querySelectorAll('details[open]');
    detailsElements.forEach((details) => {
      details.removeAttribute('open');
    });
  }
});
</script>

Accessibility

The dropdown is fully accessible and can be controlled with a keyboard. The dropdown can be opened and closed with the Enter or Space key and the dropdown items can be navigated with the tab key. It is announced as a dropdown by screen readers and the dropdown items are announced as a list.

Summary

I thought this was an intertesting experiment and I hope you find it useful. It’s neat how much you can achieve with just HTML and CSS!

You might also like