javascriptbootstrap-4bootstrap-tabs

Bootstrap Tabs Vanilla JS shown event not working


I am trying to detect when a tab is shown through Vanilla JS and the event isn't working. I have looked through multiple questions about this and none of them seem to help. Here is my current code.

var aTabs = document.querySelectorAll('a[data-toggle="tab"');
console.log(aTabs);
for (let i = 0; i < aTabs.length; i++) {
  console.log(aTabs[i].id);
  aTabs[i].addEventListener('shown.bs.tab', function(e) {
    console.log("Showing content for tab: " + e.target.href);
  }, false);
}
<ul class="nav nav-tabs" id="tab-navigation" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="1link" data-toggle="tab" href="#1" role="tab" aria-controls="community" aria-selected="true">1 <span class="badge badge-primary"></span></a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" id="2link" data-toggle="tab" href="#2" role="tab" aria-controls="2" aria-selected="false">2 <span class="badge badge-primary"></span></a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" id="3link" data-toggle="tab" href="#3" role="tab" aria-controls="3" aria-selected="false">3 <span class="badge badge-primary"></span></a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" id="4link" data-toggle="tab" href="#4" role="tab" aria-controls="4" aria-selected="false">4 <span class="badge badge-primary"></span></a>
  </li>
</ul>
<div class="tab-content" id="tab-navigation-content">
  <div class="tab-pane fade show active" id="1" role="tabpanel" aria-labelledby="tab1"></div>
  <div class="tab-pane fade" id="2" role="tabpanel" aria-labelledby="tab2"></div>
  <div class="tab-pane fade" id="3" role="tabpanel" aria-labelledby="tab3"></div>
  <div class="tab-pane fade" id="4" role="tabpanel" aria-labelledby="tab4"></div>
</div>

I have the console logs to make sure I am getting all the correct values and those are correct however the addEventListener isn't adding the event. When I click through tabs they do not trigger.

All the console logs show the correct elements, just the event isn't fired when switching between tabs.


Solution

  • According to this Stack Overflow post, you cannot use ".addEventListener" for custom jQuery events (e.g. "shown.bs.tab").

    I cannot say why the jQuery ".on" version wouldn't work, though.