Using Bootstrap 4 navtabs alongside accordions to utilize the show.bs and hide.bs functionalities

Is there a method to activate the "Maintab 2 Content" and display the accordion content for "Collapsible Group Item #2" when clicking on the "Button for Maintab 2"? I am trying to implement similar functionality on other tabs as well, but I'm struggling with using events like "show.bs.tab", "show.bs.collapse", or other related events.

Feel free to review the code snippet below. You can also view the codepen demo here: https://codepen.io/graydirt/pen/eYawXvg

$(document).ready(function(){
      $('#btn-main2').on('click', function(){
        $('#main2-tab').tab('show'); 
        $('#collapseTwo').collapse('show'); 

        // Scroll to the accordion header
        setTimeout(function() {
          $('html, body').animate({
            scrollTop: $('#collapseTwo').prev('.card-header').offset().top
          }, 500);
        }, 500);
      });
    });
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7c5c8c8d3d4d3d5c6d7e79389978997">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6c61617a7d7a7c6f7e4e3a203e203e">[email protected]</a>/dist/js/bootstrap.min.js"></script>

<ul style="list-style: none" class="py-5 d-flex align-items-center justify-content-center">
    <li class="px-2">
      <a id="btn-main2" class="btn btn-primary text-white" role="button">Button for Maintab 2</a>
    </li>
  </ul>

  <ul class="nav nav-tabs" id="myTab" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" id="main1-tab" data-toggle="tab" href="#main1" role="tab" aria-controls="home" aria-selected="true">Maintab 1 Content</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="main2-tab" data-toggle="tab" href="#main2" role="tab" aria-controls="profile" aria-selected="false">Maintab 2 Content</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="main3-tab" data-toggle="tab" href="#main3" role="tab" aria-controls="contact" aria-selected="false">Maintab 3 Content</a>
    </li>
  </ul>

  <div class="tab-content" id="myTabContent">
    <div class="tab-pane fade show active" id="main1" role="tabpanel" aria-labelledby="home-tab">main1</div>
    <div class="tab-pane fade" id="main2" role="tabpanel" aria-labelledby="profile-tab">
      <div id="accordion">
        <div class="card">
          <div class="card-header">
            <h5 class="mb-0">
              <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true">
                Collapsible Group Item #1
              </button>
            </h5>
          </div>
          <div id="collapseOne" class="collapse show" data-parent="#accordion">
            <div class="card-body">
              <!-- Accordion content here -->
            </div>
          </div>
        </div>

        <div class="card">
          <div class="card-header">
            <h5 class="mb-0">
              <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false">
                Collapsible Group Item #2
              </button>
            </h5>
          </div>
          <div id="collapseTwo" class="collapse" data-parent="#accordion">
            <div class="card-body">
              <!-- Accordion content for item #2 goes here -->
            </div>
          </div>
        </div>

        <div class="card">
          <div class="card-header">
            <h5 class="mb-0">
              <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false">
                Collapsible Group Item #3
              </button>
            </h5>
          </div>
          <div id="collapseThree" class="collapse" data-parent="#accordion">
            <div class="card-body">
              <!-- Accordion content for item #3 goes here -->
            </div>
          </div>
        </div>

      </div>
    </div>
    <div class="tab-pane fade" id="main3" role="tabpanel" aria-labelledby="contact-tab">main3</div>
  </div>

Answer №1

Utilize jQuery to handle the click event of your button and switch to the second tab. Assign the id "btn-main2" to the button.

 $(document).ready(function(){
      $('#btn-main2').on('click', function(){
        $('#main2-tab').tab('show'); 
        $('#collapseTwo').collapse('show'); 

        // Scroll to the accordion header
        setTimeout(function() {
          $('html, body').animate({
            scrollTop: $('#collapseTwo').prev('.card-header').offset().top
          }, 500);
        }, 500);
      });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d0f0202191e191f0c1d2d59435d435d">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cfef3f3e8efe8eefdecdca8b2acb2ac">[email protected]</a>/dist/js/bootstrap.min.js"></script>
<ul style="list-style: none" class="py-5 d-flex align-items-center justify-content-center">
    <li class="px-2">
      <a id="btn-main2" class="btn btn-primary text-white" role="button">Button for Maintab 2</a>
    </li>
  </ul>

  <ul class="nav nav-tabs" id="myTab" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" id="main1-tab" data-toggle="tab" href="#main1" role="tab" aria-controls="home" aria-selected="true">Maintab 1 Content</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="main2-tab" data-toggle="tab" href="#main2" role="tab" aria-controls="profile" aria-selected="false">Maintab 2 Content</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="main3-tab" data-toggle="tab" href="#main3" role="tab" aria-controls="contact" aria-selected="false">Maintab 3 Content</a>
    </li>
  </ul>

  <div class="tab-content" id="myTabContent">
    <div class="tab-pane fade show active" id="main1" role="tabpanel" aria-labelledby="home-tab">main1</div>
    <div class="tab-pane fade" id="main2" role="tabpanel" aria-labelledby="profile-tab">
      <div id="accordion">
        <div class="card">
          <div class="card-header">
            <h5 class="mb-0">
              <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true">
                Collapsible Group Item #1
              </button>
            </h5>
          </div>
          <div id="collapseOne" class="collapse show" data-parent="#accordion">
            <div class="card-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid...
            </div>
          </div>
        </div>

        <div class="card">
          ...
        </div>
        
        <div class="card">
          ...
        </div>
      </div>
    </div>
    <div class="tab-pane fade" id="main3" role="tabpanel" aria-labelledby="contact-tab">main3</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

What is the best way to implement automatic scrolling to the bottom of a materialUI drawer in React after a page refresh?

I am facing an issue with my Material UI Drawer, which contains numerous checkboxes and radio buttons for an advanced search page. Whenever a checkbox or radio button is clicked, it triggers an API request to fetch results instantly without requiring a sub ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Activate a single button to reveal hidden buttons

My HTML page is filled with numerous buttons, each designed to expand specific information upon clicking. To enhance usability, I am seeking a way to use one main button to expand all the others. Initially, I attempted to display only one button alongsid ...

Switch the background color of a list item according to a JSON search

Our organization is in need of a feature where members can be inputted into a field and the background color of the parent list item changes based on the name lookup in a JSON file. We are open to a jQuery solution, but JavaScript will also work! You can ...

Creating distinctive, unchanging colors for individual ellipses within a collection in p5.js

It's clear that each ellipse is part of a wave object, with the fill color applied on every frame causing a blinking effect. I'm trying to assign a random color to each ellipse when it's drawn, so it maintains that fill color instead of chan ...

Passing data through events from a parent component to a child component in Vue.js using the $emit method

Having trouble making this work! I have included the $emit code in my click event to trigger a custom event. <h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="$emit('addBusinessHours', null)"> ...

typescript push in react native is a crucial step to enhance performance and optimize

I've been diving into TypeScript within the realm of React Native. Oddly, when I translated a certain snippet to vanilla JavaScript, the application worked flawlessly. However, upon converting it back to TypeScript, an error message popped up stating ...

Is there a way to enclose an element with two other elements using JavaScript/jQuery

Is it possible to create a wrapping element for content located between two existing elements? Here's a code snippet to illustrate: <p> Some text some text <span class="foo">some more text</span> additional text. </p> <p> ...

Using jQuery to input a value that returns the [object Object]

While working with jQuery in asp.net, I encountered an issue where the value assigned to a hidden field (hfstockcode) is returning [object Object]. The console output shows v.fn.v.init[1]. How can I retrieve the correct value for the hidden field? $(docum ...

Utilize anonymous functions to reassign the button click event - JQuery

I'm dealing with a situation where I have 5 HTML buttons, each with a click event listener attached to it in the form of an anonymous function. For example: $('#button1').click(function(){ //some code }); At a certain poin ...

Remove letters at random from a string

Looking to randomly remove 3 letters from a string. Tried using the substr() or slice() function but struggling to choose random letters to remove. Check out my current demo below: http://jsfiddle.net/euuhyfr4/ If anyone has any suggestions, I'd g ...

Utilizing Javascript Regular Expressions to extract specified parameters from URLs with specific patterns

I am facing a specific issue with pure vanilla javascript. My task is to extract the values of A, B & C from various URL patterns, excluding any instances where the value is "XX". A, B, and C are static words that can appear in different positions wit ...

How can I dynamically modify the class name of a specific element generated during an iteration in React when another element is clicked?

My goal is to dynamically add a class to a specific element within a table row when a user clicks a remove button. The desired behavior is to disable the entire row by adding a "removed" class to the containing row div. The challenge is that there are mult ...

Exploring ways to utilize Vue data variables and methods within the configuration options of Tabulator

Utilizing tabulator in conjunction with vue using the following packages: tabulator-tables and vue-tabulator. In an attempt to implement a click event on the tabulator row, I am faced with the challenge of accessing vue data variables within the scope of ...

What is the reason behind the length property belonging to an array object?

While there are other instances, let's focus on the length property for now. Why does it appear as if we're copying it here: [].hasOwnProperty("length") //==> true It is common knowledge that an array's length property belongs ...

What are the differences between Node's bcrypt and bcryptjs libraries?

When it comes to using bcrypt in Node, the abundance of libraries available can be overwhelming. Among the top packages on npm are bcrypt with 247k downloads per month bcryptjs with 337k downloads per month (any other options worth considering?) What s ...

The function .innerHTML is not functioning correctly, at least in my opinion

When I utilize .innerHTML to insert text into a textarea, the script stops functioning if I manually begin editing the text in the textarea. Here is the code snippet: (function($){ addPort = function(name) { switch(name) { case 'name1': ...

Issue adding dictionary value to an array in JavaScript

Let's analyze the code snippet below: var array = []; var obj = [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}] for (x in obj){ array.push(x.name) } After running this code, the array ends up with the correct length but ...

Hold on until the page is reloaded: React

My current setup includes a React Component that contains a button. When this button is clicked, a sidePane is opened. What I want to achieve is refreshing the page first, waiting until it's completely refreshed, and then opening the sidepane. Below i ...

Problem with Bootstrap 5.3 navbar dropdown functionality not functioning as expected

I'm facing an issue with my code. I attempted to use both bootstrap 5.2 and 5.1, but neither seems to be working for me. I've tried opening it in both Chrome and Firefox, but the dropdown functionality is not functioning in either browser. Does a ...