Simple accordion-collapsible element with vanilla js and simple animation effect


Simple accordion-collapsible element with vanilla js and simple animation effect Tutorial by Mirko Zovko | 28. Jun. 2020.

How to create simple accordion element with vanilla js

In this article I’ll show you how to create a simple accordion (collapsible) element using only vanilla (pure) javascript without jQuery or any other library. You want to get your site as optimized as much you can, so you need to avoid using jQuery or any other similar library for just simple elements like for example accordion when you can create element like that without any problem in pure javascript.

For example jQuery has more than 10000 rows of code, and the size of the minified version has 331kb. So avoiding it you will automatically save 331kb space for your site. That maybe doesn't look too much but in the web world speed is very crucial. In some of the future articles I’ll write more about website optimization and speed. Let us now focus on simple accordions.

First what we need to create is html structure and style for our simple accordion element.

  • accordion - container for whole accordion elements
  • a-container - container for only one accordion element
  • a-btn - button for accordion activation with accordion title and icon that indicate is accordion open or close created with span element
  • a-panel - is content container, you can add here whatever you want that your accordion element holds

Basically all the work is done in the css. By adding active class on a-container element that accordion element content becomes visible. From the code below you can see that the only difference in active class is adding a different style for a-panel element. Adding opacity and max-height on a-panel, a-panel is spreading and becoming visible.

Only thing that is left to be done in vanilla javascript is to add or remove class on mouse click. For that I created a function called initAcc that receives two parameters:

  • elem - accordion element class name
  • option - that can be true or false. With the true option only one accordion panel will be opened, the other one will be automatically closed. With the false option you can open all accordions. Accordion will be closed only when you click on it again.

To start accordion, you only need to call function initAcc('.accordion, true); or initAcc('.accordion', false); depend what you need.

Full working code with both example you can check on jsFiddle or on the Codepen.

I hope you liked this article. In the next one I'll write about simple tabs with pure js. I'm planing to write series of articles with pure js elements to help you avoid big libraries and to optimize your code. If you have some suggestion or idea feel free to write in comment section bellow. Enjoy! :)