I'm using bootstrap tabs in one of my application and I have a challenge where shown.bs.tab event is not getting triggered when page is loaded with default active tab.
In the below code I have a tab named "Home" which is an default tab (active class added). On page load, my "Home" tab content is shown perfectly, but the challenge is the 'shown.bs.tab' event attached to that tab is not triggered. The same event is triggered when I navigate to "Menu 1" tab and then come back to "Home" tab.
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#home">Home</a></li>
<li><a data-toggle="tab" href="#menu1">Menu 1</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade in active">
<h3>HOME</h3>
<p>Some content.</p>
</div>
<div id="menu1" class="tab-pane fade">
<h3>Menu 1</h3>
<p>Some content in menu 1.</p>
</div>
</div>
<script>
$(document).ready(function(){
$("a[href='#home']").on('shown.bs.tab', function (e) {
alert('tab shown');
});
});
</script>
How do I make this event trigger on page load? The intention behind this is content of "Home" tab is dynamic which is response of Ajax call which gets triggered on tab is shown.
Solved this by removing "active" class from HTML and adding script to select the tab to be shown by default.
Below is the updated script.
<script>
$(document).ready(function(){
$("a[href='#home']").on('shown.bs.tab', function (e) {
alert('tab shown');
}).tab('show');
});
</script>
With this script, when the "Home" tab is shown, the event gets triggered. Also, the same is triggered when navigated back from other tabs.