How to use details/summary tag as an accordion

← Blog

Here’s a quick trick to display content as accordions on mobile but as static content on desktop, using the details html tag.

Why do this?

This technique is especially useful when there is content that is suitable to be collapsed on mobile, but can remain fully visible on desktop. And, rather than complicate features by adding unnecessary JavaScript (or libraries), this method takes advantage of standard HTML features: details / summary

Here’s our HTML. It’s important to note that the details tags should be open by default.

<section id=“the-details”>
  <details open>
    <summary>Title for the content…</summary>
    <div>
      <p>Content goes here…</p>
    </div>
  </details>
</section>

This little bit of javascript checks the window size and either locks or unlocks the click interaction on the summary tag.

function mobileFilters() {
  const filters = document.querySelector('#the-details');
  const details = filters.querySelectorAll('details');
  const summary = filters.querySelectorAll('summary');
  summary.forEach(function(el){
    el.addEventListener('click', function(e){
      // If the window size is greater than 1024px, prevent clicks
      // on the summary tag. This will prevent them from being closed.
      if (window.matchMedia('(min-width:1024px)').matches) {
        e.preventDefault();
      }
    });
  });
  details.forEach(function(el){
    // If the window is smaller that 1024px, remove all the “open”
    // attributes from the summary tags, so they are closed on page load
    // and can be expanded on click/tap.
    if (window.matchMedia('(max-width:1023px)').matches) {
      el.removeAttribute('open');
    }
  });
}
mobileFilters();

Subscribe to my newsletter

Sign up to get my latest blog articles direct to your inbox.