Simple tabs element with vanilla js and animation effect
Tutorial by Mirko Zovko | 01. Jul. 2020.
How to create simple tabs element with vanilla js
As always, first we need to create html structure and style for our simple tabs element:
- t-btn-container - is a container for all tabs button, so you can easily add your style to it
- t-btn - is a tab button, clicking on it opens content for that tab
- data-name - is and attribute that I'm using for opening right tab panel, same name from data-name attribute need to be added as a class for right t-panel that you want to open
- t-panel-container - is a container for all tabs panel
- t-panel - is a container for tab content, in here you can add any html element you want, and as many you want
To make it all work I'm using active class. But this time needs to be added on two places. One active for active t-btn (tab button) and second active for active t-panel (panel with content). You can look all scss below. This style is for horizontal tabs element. I create also one more style for vertical tabs element and you can check in on jsFiddle.
Last and most important part is to create vanilla js function that adding life to our tabs element. For that I created initTab function that receive one parameter elem, that is the html element of tabs element you created. Creating this in that way you can create multiple tabs element on the same page. Commented js function you can check below.
I hope you liked this article. This is second article in series of creating simple elements with vanilla (pure) js avoiding big libraries. If you have some suggestion or idea feel free to write in comment section bellow. Enjoy! :)