I have implemented the demo js of MDC tabs found here and it's working fine. How would I go about converting this to be more re-usable so I could just use a generic selector like ".js-tabs", link them with tabs id="tab1" then the panels with for="tab1" and include that one piece of js in my main js file.
This is just a prototype so don't have to worry about writing production ready code.
Pen
https://codepen.io/rhysyg03/pen/OgRygJ
MDC Links
https://material-components-web.appspot.com/tabs.html
https://github.com/material-components/material-components-web/blob/master/demos/tabs.html
var tabs = new mdc.tabs.MDCTabBar(document.querySelector('#tab1'));
var panels = document.querySelector('.js-panels');
tabs.preventDefaultOnClick = true;
function updatePanel(index) {
var activePanel = panels.querySelector('.js-panel.is-active');
if (activePanel) {
activePanel.classList.remove('is-active');
}
var newActivePanel = panels.querySelector('.js-panel:nth-child(' + (index + 1) + ')');
if (newActivePanel) {
newActivePanel.classList.add('is-active');
}
}
tabs.listen('MDCTabBar:change', function (t) {
var tabs = t.detail;
var nthChildIndex = tabs.activeTabIndex;
updatePanel(nthChildIndex);
});
And my HTML
<div class="mdc-toolbar">
<div class="mdc-toolbar__row">
<div class="mdc-toolbar__section mdc-toolbar__section--align-start">
<nav id="tab1" class="mdc-tab-bar mdc-tab-bar--indicator-accent js-tabs" role="tablist">
<a role="tab" aria-controls="panel-1"
class="mdc-tab mdc-tab--active">Item One</a>
<a role="tab" aria-controls="panel-2"
class="mdc-tab">Item Two</a>
<a role="tab" aria-controls="panel-3"
class="mdc-tab">Item Three</a>
<span class="mdc-tab-bar__indicator"></span>
</nav>
</div>
</div>
</div>
<section>
<div class="js-panels" for='tab1'>
<p class="js-panel is-active" role="tabpanel" aria-hidden="false">Item One</p>
<p class="js-panel" role="tabpanel" aria-hidden="true">Item Two</p>
<p class="js-panel" role="tabpanel" aria-hidden="true">Item Three</p>
</div>
</section>