Bootstrap Tabs: How to close a tab from a button within a tab-content pane? Need help from the CSS Pros

I have the following use case with Bootstrap Tabs:

I would like to start a page with all tabs closed.

On the Link element I deleted the active class and changed aria-selected="true" to false:

<li class="nav-item">
    <a class="nav-link" id="navTabs1_1_tab" data-bs-toggle="tab" href="#" data-bs-target="#navTabs1_1" role="tab" aria-controls="navTabs1_1" aria-selected="false">Home</a>
</li>

On the content element I deleted the class show active:

<div class="tab-pane fade" id="navTabs1_1" role="tabpanel">
  <p>Consequat occaecat ullamco amet non eiusmod nostrud dolore irure incididunt est duis anim sunt officia. Fugiat velit proident aliquip nisi incididunt nostrud exercitation proident est nisi. Irure magna elit commodo anim ex veniam culpa eiusmod id nostrud sit cupidatat in veniam ad. Eiusmod consequat eu adipisicing minim anim aliquip cupidatat culpa excepteur quis. Occaecat sit eu exercitation irure Lorem incididunt nostrud.</p>
</div>

So far so good. Now my problem: How can I close the tab from a button inside a tab content pane on click so that I have all closed again?

Give the button a class of close or similar and add the following script:

$(“button.close”).click(function(){
$(“ul li a”).removeClass(“active”);
$(".tab-content div").removeClass(“active”);
});

2 Likes

Thank you @ben for your snippet. I have to admit that I never used custom Javascript before. How do I use the code and is it necessary to bind it to a specific id (id="navTabs1_tabs")? :grimacing:

There are two ways to include scripts

  1. external JS file linked to the document
  2. placed in the document.

If choosing 2., place the code at the bottom of the document, just above the closing HTML tag, between <script> and </script>

When choosing 2., there may not be a necessity to define the selector any further. When choosing 1,. there would be an argument to define the selector with a unique ID

1 Like

How would I define the unique ID in the selector if I should need it?

Like this?

$("button.close").click(function(){
$("navTabs1_tabs ul li a").removeClass("active");
$("navTabs1_tabs .tab-content div").removeClass("active");
});

Prefix the ID identifier as #. If a Class identifier use .

$(“button.close”).click(function(){
$("#navTabs1_tabs ul li a").removeClass(“active”);
$("#navTabs1_tabs .tab-content div").removeClass(“active”);
});

1 Like

Great! Thanks a lot for your help.

1 Like