Search code examples
javascriptjquerytwitter-bootstrapbootstrap-tabs

Is there a way to use bootstrap tabs without using a unique identifier


I would like to be able to use bootstrap tabs but without using a unique selector.

I cannot guarantee that the selector is the only one in the dom.

I have many sub templates which are either included in the page as it is rendered or can be loaded inside a modal via ajax.

I do use id's but never in the templates i might use within a modal, some modals are preloaded after the page load event.

  <div class="panel">
    <div class="panel-heading">
       <ul class="nav nav-tabs">
        <li><a data-target=".pane1" data-toggle="tab" aria-expanded="true">pane 1</a></li>
        <li><a data-target=".pane2" data-toggle="tab" aria-expanded="true">pane 2</a></li>
      </ul>     
    </div>
    <div class="panel-body">
      <div class="tab-content">
        <div class="tab-pane pane1">pane 1</div>
        <div class="tab-pane pane2">pane 2</div>
      </div>
    </div>
  </div>

I have tried an onclick event on the anchor tag with just jquery which is less than ideal, but cannot get it to work with the .tab('show')

onclick="$(this).closest('.panel')
   .find('.tab-pane').hide();$(this).closest('.panel').find('.pane1').show();"

Solution

  • Yes it is possible...for this HTML:

     <div class="panel">
        <div class="panel-heading">
           <ul class="nav nav-tabs">
            <li><a href="#">pane 1</a></li>
            <li><a href="#">pane 2</a></li>
          </ul>     
        </div>
        <div class="panel-body">
          <div class="tab-content">
            <div class="tab-pane">pane 1</div>
            <div class="tab-pane">pane 2</div>
          </div>
        </div>
      </div>
    

    This Javascript:

    $('.panel .nav-tabs').on('click', 'a', function(e){
      var tab  = $(this).parent(),
          tabIndex = tab.index(),
          tabPanel = $(this).closest('.panel'),
          tabPane = tabPanel.find('.tab-pane').eq(tabIndex);
      tabPanel.find('.active').removeClass('active');
      tab.addClass('active');
      tabPane.addClass('active');
    });
    

    See this functioning bootply

    Note Take note that I removed all data attributes from the anchors to prevent bootstraps auto wireup to them**