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
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.
- 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.
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! :)