Bootstrap 4 tabs: get index number of clicked tab?

Viewed 1150

I am trying to figure out which tab the user clicked on by its index, e.g. they clicked on the second of five tabs.

I can get the total number of tabs by adding an ID to the nav:

this.numTabs = $('#myTabset').children().length;

from the Bootstrap 4 docs, I can get the clicked tab:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
      console.log(e.target); // newly activated tab
    });

Which logs:

<a class="nav-link" data-toggle="tab" href="#profileS" role="tab" aria-selected="false">Profile</a>

So I can get all aspects of the clicked tab, but how to get which "number" tab it is?

2 Answers

Use the jQuery .index() method like this...

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    var idx = $(this).index('a[data-toggle="tab"]');
});

Demo: https://www.codeply.com/go/GeNHX340fc

If you want to get the index of the currently selected tab, do the below

let tabIndexNumber = $('#myTab a[aria-selected="true"]').index('a[data-toggle="tab"]');

The id #myTab is the id of the bootstrap tab. It produces a zero-based numeric value, zero being the first tab.

Related