Skip to content
Advertisement

How to use JavaScript to apply slidedown functionality in accordion?

In this snippet below, I’m trying to apply a slide down functionality to each panel when opened. The result is that slide down is working.

The problem is…

  1. In mobile, when a second panel is opened, the first panel remains at full height.

  2. Slide up functionality isn’t working as expected.

Lastly, I have hundreds of these accordions on my site. I need to be able to update the JS/CSS accordingly, without changing the HTML markup.

How do I apply JavaScript slide up/down functionality to accordion panels when opened?

JavaScript
JavaScript
JavaScript

Advertisement

Answer

Since you can’t transition/animate between height:0px and auto you might try this approach:

We’re hiding all accordion contents on load in a way that still allows us to calculate their individual heights by js.

JavaScript

We can now store these height values as a data-attribute added to each accordion body.
When a accordion section gets expanded, this height value is applied as a max-height inline-style.

Example 1: Accordion

JavaScript
JavaScript
JavaScript

You might also need a window resize event handler to recalculate heights, when the window resizing occurs.

I also strongly recommend to add appropriate aria-attributes for better accessibility.

Example 2: height checking on click

JavaScript
JavaScript
JavaScript

Edits:
To improve accessibility, collapsed accordion have visibility set to hidden to prevent hidden elements from getting focus (try to navigate via Tab key).
Basic ARIA attributes for visibility states can be added automatically.

This snippet will calculate the necessary max-height values on click via element.scrollHeight
Be careful: due to reflows this value might change after exapanding the accordion – therefore you might need some additional height like
let accHeight = acc.scrollHeight * 1.5;

There is also a “no-js” fallback to ensure all content is displayed, when js is disabled.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement