Pure JavaScript Accordion Example With Sliding Animation

Write accordion feature in plain JavaScript might be a little tricky, especially if you want to provide nice sliding animation.

Accordion code is written in ES6 version of JavaScript.

There is an option “singleMode”, if you want to have only one opened at the time, or more contents can be visible simultaneously.

Accordion Example

Sliding Effect

If you want to have sliding effect, keep in mind:

  1. do not set height via CSS
  2. do not set content “display:none;” via CSS
  3. hide it dynamically with JavaScript
  4. enable smooth CSS transition on content box

This is important, because original height is kept in “data-height” attribute, only then content is hidden after load. Now, when you know the height, you can set it to the activated item.

Finally, don’t forget to disable content flow out of the box with CSS “overflow:hidden;” property.

Animation itself is held by means of simple CSS transition property. Check CSS tab in the JSFiddle.

How do you implement accordion feature?