Markup for an animated <details>

The native <details> element requires a <summary>, which is what stays visible while the accordion is closed; everything else inside <details> forms the collapsing body. Wrapping that body in a <div> gives the animation a single element to measure and target.

<details>
  <summary>Summary of the accordion</summary>
  <div class="content">
    <p>
      Lorem, ipsum dolor sit amet consectetur adipisicing elit.
      Modi unde, ex rem voluptates autem aliquid veniam quis temporibus repudiandae illo, nostrum, pariatur quae!
      At animi modi dignissimos corrupti placeat voluptatum!
    </p>
  </div>
</details>

Building an Accordion class

A reusable Accordion class lets you call new Accordion() on each <details> on the page.

class Accordion {
  // The default constructor for each accordion
  constructor() {}

  // Function called when user clicks on the summary
  onClick() {}

  // Function called to close the content with an animation
  shrink() {}

  // Function called to open the element after click
  open() {}

  // Function called to expand the content with an animation
  expand() {}

  // Callback when the shrink or expand animations are done
  onAnimationFinish() {}
}

State kept in the constructor

The constructor holds all per-accordion data.

constructor(el) {
  // Store the <details> element
  this.el = el;
  // Store the <summary> element
  this.summary = el.querySelector('summary');
  // Store the <div class="content"> element
  this.content = el.querySelector('.content');

  // Store the animation object (so we can cancel it, if needed)
  this.animation = null;
  // Store if the element is closing
  this.isClosing = false;
  // Store if the element is expanding
  this.isExpanding = false;
  // Detect user clicks on the summary element
  this.summary.addEventListener('click', (e) => this.onClick(e));
}

Intercepting clicks in onClick()

The click handler bails out if the element is mid-animation, so rapid clicks cannot make the accordion jump from fully open to fully closed. The browser sets the [open] attribute on <details> when it expands; the class reads that state via this.el.open.

onClick(e) {
  // Stop default behaviour from the browser
  e.preventDefault();
  // Add an overflow on the <details> to avoid content overflowing
  this.el.style.overflow = 'hidden';
  // Check if the element is being closed or is already closed
  if (this.isClosing || !this.el.open) {
    this.open();
  // Check if the element is being openned or is already open
  } else if (this.isExpanding || this.el.open) {
    this.shrink();
  }
}

Collapsing with shrink()

This method calls WAAPI's .animate(), which works much like CSS @keyframes: you define start and end keyframes. Only two are needed here — the element's current height, held in startHeight, and the closed height in endHeight, which equals the height of the <summary>.

shrink() {
  // Set the element as "being closed"
  this.isClosing = true;

  // Store the current height of the element
  const startHeight = `${this.el.offsetHeight}px`;
  // Calculate the height of the summary
  const endHeight = `${this.summary.offsetHeight}px`;

  // If there is already an animation running
  if (this.animation) {
    // Cancel the current animation
    this.animation.cancel();
  }

  // Start a WAAPI animation
  this.animation = this.el.animate({
    // Set the keyframes from the startHeight to endHeight
    height: [startHeight, endHeight]
  }, {
    // If the duration is too slow or fast, you can change it here
    duration: 400,
    // You can also change the ease of the animation
    easing: 'ease-out'
  });

  // When the animation is complete, call onAnimationFinish()
  this.animation.onfinish = () => this.onAnimationFinish(false);
  // If the animation is cancelled, isClosing variable is set to false
  this.animation.oncancel = () => this.isClosing = false;
}

Preparing to open in open()

Expansion is split into two steps. open() first measures the <details> height and writes it as an inline style. Setting the open attribute then reveals the content, but overflow: hidden plus the fixed height keeps it visually clipped. After waiting for the next frame, the method calls expand() to run the animation.

open() {
  // Apply a fixed height on the element
  this.el.style.height = `${this.el.offsetHeight}px`;
  // Force the [open] attribute on the details element
  this.el.open = true;
  // Wait for the next frame to call the expand function
  window.requestAnimationFrame(() => this.expand());
}

Animating outward in expand()

Like shrink(), but running the other way: the keyframes go from the element's current height to the end height, which is the summary height plus the height of the inner content.

expand() {
  // Set the element as "being expanding"
  this.isExpanding = true;
  // Get the current fixed height of the element
  const startHeight = `${this.el.offsetHeight}px`;
  // Calculate the open height of the element (summary height + content height)
  const endHeight = `${this.summary.offsetHeight + this.content.offsetHeight}px`;

  // If there is already an animation running
  if (this.animation) {
    // Cancel the current animation
    this.animation.cancel();
  }

  // Start a WAAPI animation
  this.animation = this.el.animate({
    // Set the keyframes from the startHeight to endHeight
    height: [startHeight, endHeight]
  }, {
    // If the duration is too slow of fast, you can change it here
    duration: 400,
    // You can also change the ease of the animation
    easing: 'ease-out'
  });
  // When the animation is complete, call onAnimationFinish()
  this.animation.onfinish = () => this.onAnimationFinish(true);
  // If the animation is cancelled, isExpanding variable is set to false
  this.animation.oncancel = () => this.isExpanding = false;
}

Cleanup in onAnimationFinish()

Both animations end here. The [open] parameter is true when the accordion is open, and the function applies the [open] HTML attribute itself, since the browser is no longer managing that state.

onAnimationFinish(open) {
  // Set the open attribute based on the parameter
  this.el.open = open;
  // Clear the stored animation
  this.animation = null;
  // Reset isClosing & isExpanding
  this.isClosing = false;
  this.isExpanding = false;
  // Remove the overflow hidden and the fixed height
  this.el.style.height = this.el.style.overflow = '';
}

Wiring up every <details>

Instantiate one Accordion per element by querying all <details> tags with querySelectorAll.

document.querySelectorAll('details').forEach((el) => {
  new Accordion(el);
});

Constraints imposed by the height math

  • The <summary> and the inner content must keep the same height at all times, because the open and closed heights are computed from them. Adding padding to the summary only when open, for instance, will cause jumps.
  • Keep the inner content at a fixed height and avoid content whose height changes during the opening animation.
  • Do not put a margin between the summary and the content — it is not accounted for in the height keyframes. Use padding on the content for spacing instead.