stabs.js is a JavaScript library for wiring up tabbed sections in your web page markup.
The lib is just shy of 3KB in size before minification.
It’s not something I’m proud of. It’s not the friendliest or the most modern approach. There's no fancy prototypal inheritance involved, it just looks for markup classified as a tabcontainer, looks for tabs and tabpanels within, and wires up the click events.
However, it’s easy to use, it conforms to web accessibility guidelines, and it will work in basically any browser made after IE7 without polyfills. If you polyfill querySelector, it may even work in IE7.
Why make this lib?
Bootstrap and other libraries/frameworks tend to require jQuery. Not surprising. My 50 lines of vanilla would probably be about 8 lines of jQuery.
However, it is 2016 and while ES5/ES6 are gaining traction, their best features have to be polyfilled. My aim was to create tabs accessibly without jQuery or polyfills. The ES3 that is actually supported in the real world is now largely standardised even in IE since IE9.
There are of course other vanilla JS alternatives, but they all force hash fragments, and that's a feature I really didn‘t want.
I wanted something simple and robust.
And thus, stabs.js was born.
How does it work?
stabs.js uses only vanilla JavaScript primarily relying on for loops, indexOf, setAttribute and className.
This small lib loops through everything in the DOM and adds event listeners to everything that is a “tab” in a tabcontainer.
These event listeners wait for a tab to be clicked and then, if the tab is not active, it and its corresponding tabpane are given an active CSS class and all other tabs/tabpanes have their active status removed.
This might seem like cheating, but the approach could easily be adapted to manipulate styles directly. However, appending and removing classes is ultimately more efficient, and also enables the exact way tabs are displayed/hidden to be very flexible to the CSS-savvy dev.
This is ultimately the simplest way to work with tabs. You’ll be using a CSS class to reflect that the tab is active anyway (or alternatively data-attributes, but they’re slower and not supported in old IE).
How does one use it?
Include stabs.js in your page and set up the basic markup as it is on this website.
Set up some CSS to govern how tabs appear when not visible etc.