How to programmatically select a tab?

dflorey picture dflorey · Jul 12, 2015 · Viewed 7.9k times · Source

I am using a mdl tabbar from the layout component page.

  <header class="mdl-layout__header">
    <div class="mdl-layout__header-row">
      <!-- Title -->
      <span class="mdl-layout-title">Title</span>
    </div>
    <!-- Tabs -->
    <div class="mdl-layout__tab-bar mdl-js-ripple-effect">
      <a href="#fixed-tab-1" class="mdl-layout__tab is-active">Tab 1</a>
      <a href="#fixed-tab-2" class="mdl-layout__tab">Tab 2</a>
      <a href="#fixed-tab-3" class="mdl-layout__tab">Tab 3</a>
    </div>
  </header>

Do I have to add/remove the "is-active" class on both tab / panel or is there a simpler way to select a tab programmatically?

Answer

DMack picture DMack · Jul 14, 2015

As far as I can tell, manually changing the is-active class on the tabs (.mdl-layout__tab) and the tab panels (.mdl-layout__tab-panel) does produce the desired results, though.

With jQuery:

            // remove all is-active classes from tabs
            $('a.mdl-layout__tab').removeClass('is-active');
            // activate desired tab
            $('a[href="#fixed-tab-2"]').addClass('is-active');
            // remove all is-active classes from panels
            $('.mdl-layout__tab-panel').removeClass('is-active');
            // activate desired tab panel
            $('#fixed-tab-2').addClass('is-active');