Simple tabs element with vanilla js and animation effect

purejsjavascripttabshtmlcss

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


In this tutorial I'll show you how to create simple tabs element using only vanilla, pure javascript without jQuery or any other library. As I mentioned in last article, you want to get your site optimized as much as you can, so for simple element like this one try not to use jQuery or any other library when you can create this in vanilla javascript.

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.


Full working code with both example, horizontal and vertical, you can check bellow or on jsFiddle or Codepen.



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