Issue with Vanilla JS not firing the shown event in Bootstrap tabs

I am struggling to identify when a tab is displayed using Vanilla JS, but the event doesn't seem to be working. Despite researching various solutions, none of them have been helpful in resolving this issue. Here's my current code snippet.

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>

  // Remaining list items abbreviated for brevity

</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>

  // Remaining tab elements abbreviated for brevity

</div>

Although all console logs indicate correct values, the addEventListener method isn't being attached to the tabs. As a result, clicking through different tabs fails to trigger the event as expected.

While the console outputs display accurate information about elements, the event simply does not fire upon switching between tabs.

Answer №1

As mentioned in a previous discussion on Stack Overflow, it's been noted that using ".addEventListener" does not support custom jQuery events like "shown.bs.tab".

The reason for the limitation with the jQuery ".on" method is still unclear.

Answer №2

During the year 2023, while utilizing Bootstrap 5.3 on Firefox version 111.0.1, I encountered no issues with the use of (addEventListener).

var tabEl = document.querySelectorAll('button[data-bs-toggle="tab"]');
for (let i = 0; i < tabEl.length; i++) {
   console.log(tabEl[i].id);
   tabEl[i].addEventListener('shown.bs.tab', function(e) {
     console.log("Displaying content for tab: " + e.target.href);
   }, false);
}

Answer №3

Your event listener was set up incorrectly because you didn't specify which event you wanted to listen for. To listen for tab selection, you should pass the click event handler.

Check out this JSFiddle for a working example: http://jsfiddle.net/97nq823z/

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('click', writeToConsole(aTabs[i]));
}

function writeToConsole(tab) {
console.log(tab);
}
<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The integration of numerous filters in the Google Maps API allows for complex intersection

After weeks of searching, I finally found a solution for filtering multiple criteria using JavaScript and the Google Maps API. The functionality I found is exactly what I need for my map, but I'm struggling to get it to work properly. Can someone help ...

Problem with assigning onclick to a function

I've been working on adding an onclick function to my code, using the following line: newbutton.onclick = whoWon(this.id) Here's some other relevant code: var winner; function whoWon(name){ winner = name; } The issue I'm facing is tha ...

Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a ...

Is there a way for me to choose all the classNames that conclude with a specific word within the MUI sx property?

I am currently working with MUI and I have a need to modify certain properties that are prefixed with random IDs. How can I target, for instance, the first one using: '& endsWith(MuiAccordionDetails-root)' I wish to achieve this because the ...

The Nodejs application running on Heroku encountered issues while attempting to create products, whereas it functions perfectly on localhost

I've developed a Node.js app that allows students to post ads for items they want to sell. The app is hosted on Heroku, but there seems to be an issue where users are unable to see the ads they create after logging in and navigating to their dashboard ...

Select/Deselect all, no modification to the arrangement HTML/JavaScript

Currently in the process of building a simple website, I've hit a snag. I have various checkboxes that allow users to toggle certain elements on and off (primarily for layout purposes) and I've implemented a check/uncheck all button. The issue ...

Retrieve the price of a span element based on the selected radio button using jQuery

I have a span with the class .amount, and now I want to extract the price from that span. $('.dimension-layer-dimension').click(function() { // Here is my JavaScript attempt var price4 = $(this).find('radio:checked').data(&apo ...

Implement pagination for an array in JavaScript

I am seeking a solution involving displaying a JavaScript object in a paged format. For instance, given the sample object below, I aim to present it as pages based on the value stored in the perPage variable. { "fruits":[ { "from":"Shanghai ...

Techniques for incorporating a variable into the value field in JavaScript

let y = data[1]; cell1.innerHTML ='<input id="text" type="text" value= "'y'"/>' ; This snippet of code does not render any content when attempting to pass the variable, but if you provide a specific value like "h", it will displa ...

Searching and filtering arrays in Javascript

Creating a new array based on keyword is what I am aiming for. If my search key word is "align-center" the result should be ["align-center"] "align" the result should be ["align-left", "align-center", "align-right"] "right" the result should be ["alig ...

Switching the theme color from drab grey to vibrant blue

How can I change the default placeholder color in md-input-container from grey to Material Blue? I have followed the instructions in the documentation and created my own theme, but none of the code snippets seems to work. What am I doing wrong? mainApp. ...

Alert event in JavaScript navigating between different pages

My website features two dynamic php pages: customer invoices and customer management. One common request from my users is the ability to swiftly add a new customer directly from the customer invoices page. Instead of cluttering the customer invoices page ...

What is the best way to swap out particular phrases within HTML documents or specific elements?

Trying to update specific strings within an HTML document or element. How do I go about parsing and replacing them? To clarify: - Identify all instances of #### in element .class - Swap them out with $$$$$ Currently utilizing jQuery for this task. Appre ...

Send properties to function in jQuery and Rails

I'm working on sending data through jQuery ajax to a custom method in my controller. This will help me create dynamic database queries by using values from a dropdown menu as the search criteria. Here's my method: class PublicController < Ap ...

Enable scrolling feature for the table

I have integrated a bootstrap table into my React application, but I am facing an issue where the table is not scrollable. Whenever new content is loaded, it increases the height of the table instead of making it scrollable. Below is the code for my table ...

What is the best way to make a div stick to the inside of another div with Bootstrap?

As a newcomer to Bootstrap 4, I am curious if there is a way to affix a div to the bottom of its parent div. My structure involves using the classes .container within a .row, along with several child divs: <div class='container'> <d ...

Is it possible to generate a JS error from Go web assembly?

I attempted js.Global().Call("throw", "yeet") However, I encountered panic: 1:1: expected operand, found 'type' [recovered] wasm_exec.f7bab17184626fa7f3ebe6c157d4026825842d39bfae444ef945e60ec7d3b0f1.js:51 panic: syscall/js ...

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

Displaying a message below the submission box notifying the user that they have not entered any information

After a week of diving into HTML and JavaScript, I have a question. How can I display text below the input box for first and last name? This text should inform the user that they left it blank when submitted. <!DOCTYPE html> <html> <head ...

Assistance is required for establishing a connection between php and js. The process begins with executing a sql query to extract the necessary data, which is then encoded into JSON format

I have encountered an issue with a project I am working on solo, involving a sidecart in a PHP file with external links to SQL, CSS, and JS. The problem arose when attempting to insert necessary data into JS using JSON encoding. <?php session_start(); ...