user3033194
user3033194

Reputation: 1821

Tab event not firing for default tab

I have 3 tabs, of which 1 is active when the page loads. I have associated an event with the tabs. The code is given below:

HTML:

<ul class="nav nav-tabs nav-justified">
    <li class='active'><a href="#id1" data-toggle="tab" id="q0" class="qtab"></a></li>
    <li><a href="#id2" data-toggle="tab" id="q1" class="qtab"></a></li>
    <li><a href="#id3" data-toggle="tab" id="q2" class="qtab"></a></li>
</ul>

JS:

$('.qtab').on("shown.bs.tab", function(event){
    var elem = $(this).attr("id");
    alert(elem);
});

The alert box is displayed when the tab is changed, but not when the default tab (ID 'q0') is displayed. Does anyone know how I can fire the event for the default tab as well? Thanks in advance!!

Upvotes: 2

Views: 568

Answers (1)

Sabrina
Sabrina

Reputation: 617

According to the Bootstrap documentation for Tab Events:

shown.bs.tab: (on the newly-active just-shown tab, the same one as for the show.bs.tab event)

You have to dig around for the subtext here, but it looks like this event is only fired on an active tab change. To get around this, remove the active class from your first tab (because the event also won't be fired if the tab is already active) and set the active tab in your jQuery on page load with the following line (also from the Bootstrap documentation):

$('.nav a[href="#id1"]').tab('show') // Select tab by name

See my updated fiddle for demonstration.

Upvotes: 4

Related Questions