What is the best way to ensure that only one accordion tab remains open at a time, preventing it from closing unless a different tab

How can I ensure that only one accordion tab is open at a time, automatically closing any others that are currently open?

Here is my current code for the accordion:

$('[data-bs-toggle="collapse"]').on('click', function(e) {
  if ($(this).parents('.accordion').find('.collapse.show')) {
    var idx = $(this).index('[data-bs-toggle="collapse"]');
    if (idx == $('.collapse.show').index('.collapse')) {
      // prevent collapse
      e.stopPropagation();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77151818030403051607374259475945">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8defe2e2f9fef9ffecfdcdb8a3bda3bf">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="accordion accordion-flush" id="accordionFlush">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <div class="pannel-heading" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseTwo">
            SEO SHORT INFO SENTENCE 1
        </button>
      </div>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionFlush">
      <div class="accordion-body my-3">
        <strong>Lorem ipsum dolor sit amet consectetur adipisicing elit.</strong> Lorem ipsum dolor sit amet consectetur adipisicing elit.
        <div>
          <a href="#" class="hover-underline-animation">Enquire Now</a>
          <!-- needs spacing -->
        </div>
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
            SEO SHORT INFO SENTENCE 2
        </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionFlush">
      <div class="accordion-body">
        <strong>Lorem ipsum dolor sit amet consectetur adipisicing elit.</strong>Lorem ipsum dolor sit amet consectetur adipisicing elit.
        <div>
          <a href="#" class="btn btn-outline-dark btn-md mt-3">Enquire Now</a>
        </div>
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingThree">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
            SEO SHORT INFO SENTENCE 3
        </button>
    </h2>
    <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionFlush">
      <div class="accordion-body">
        <strong>Lorem ipsum dolor sit amet consectetur adipisicing elit.</strong> Lorem ipsum dolor sit amet consectetur adipisicing elit.
        <div>
          <a href="#" class="btn btn-outline-dark btn-md mt-3">Enquire Now</a>
        </div>
      </div>
    </div>
  </div>
</div>

I would greatly appreciate any assistance with this issue. Thank you kindly.

Answer №1

Keep track of open panels and prevent closing if it's the same panel.

Initialize by setting the default-open panel.

Utilize accordion events like:

$(".collapse").on("show.bs.collapse", function(e) {

Updated code snippet:

let target = $(".collapse:not(.collapsed)").get(0);

$(".collapse").on("show.bs.collapse", function(e) {
  target = e.target;
});

$(".collapse").on("hide.bs.collapse", function(ee) {
  if (ee.target == target)
    return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6949999828582849786b6c3d8c6d8c4">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35575a5a41464147544575001b051b07">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="accordion accordion-flush" id="accordionFlush">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <div class="pannel-heading" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseTwo">
        SEO SHORT INFO SENTENCE 1
        </button>
      </div>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionFlush">
      <div class="accordion-body my-3">
        <strong>Lorem ipsum dolor sit amet consectetur adipisicing elit.</strong> Lorem ipsum dolor sit amet consectetur adipisicing elit.
        <div>
          <a href="#" class="hover-underline-animation">Enquire Now</a>
          <!-- needs spacing -->
        </div>
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
            SEO SHORT INFO SENTENCE 2
        </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionFlush">
      <div class="accordion-body">
        <strong>Lorem ipsum dolor sit amet consectetur adipisicing elit.</strong> Lorem ipsum dolor sit amet consectetur adipisicing elit.
        <div>
          <a href="#" class="btn btn-outline-dark btn-md mt-3">Enquire Now</a>
        </div>
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingThree">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                            SEO SHORT INFO SENTENCE 3
                        </button>
    </h2>
    <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionFlush">
      <div class="accordion-body">
        <strong>Lorem ipsum dolor sit amet consectetur adipisicing elit.</strong> Lorem ipsum dolor sit amet consectetur adipisicing elit.
        <div>
          <a href="#" class="btn btn-outline-dark btn-md mt-3">Enquire Now</a>
        </div>
      </div>
    </div>
  </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

Enhancing functionality by updating a function to accept an object as input instead of individual key:value pairs in TypeScript

I'm currently tackling a challenge with a friend's icon library component, specifically with their set() function. The issue arises when I want to invoke two functions, namely setRandomColor() and setColor(), both intended to update two values w ...

Is it possible for you to enter "1.00" instead of just 1 when using the input type as number?

I am using Polymer paper-input and I would like to ensure that my input with type "number" always displays 2 decimal points, even when it is a whole number. Instead of just displaying as "1", I want it to be shown as "1.00" at all times. I have tried sett ...

During the rendering process, the property "quote" was accessed, however, it is not defined on the current instance. (Vue.js)

Every time I try to retrieve data from the kanye API, I encounter this error message: Property "quote" was accessed during render but is not defined on instance. Below is the code snippet that triggered the error: <template> <div> ...

Nginx and Socket.io: Issues with client-server connection not functioning properly

Hello everyone! I am currently in the process of deploying my application, which utilizes React and NodeJs. However, I have encountered an issue with integrating Socket.io with Nginx. My approach involves editing the Nginx file using the command: sudo ...

Using jQuery to store the name of a Div in a variable and subsequently invoking it in a function

Recently, I've been grappling with a task involving storing a div name in a variable for easier editing and incorporating it into standard actions like show/hide. My code functions perfectly without the variables, but introducing them causes the div ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Disable the outer div scrolling in VueJS, but re-enable it once the inner div has reached the bottom of

I am currently working on a webpage that contains multiple divs stacked vertically. Here is the concept I am working with: Once the scrollbar reaches the bottom of the first div, the outer scrollbar will be disabled and the inner scrollbar will be enabled ...

Documentation for Lambda function within an object

Looking to properly document the sock and data variables using JSDoc in my code. var exec = { /** * @param {Number} sock * @param {String} data */ 1: (sock, data) => { console.log("GG"); }, 2: (sock, data ...

Extract the name of elements from a JSON string

After creating a new evaluation tool, I have managed to save the answers in a specific format. {"2":"E","4":"C","5":"A"} In this case, the user responded to questions number 2, 4, and 5. Now I am looking for a way to parse each answer in a structured m ...

What is the best way to maintain a Photo's Aspect Ratio using just HTML and CSS?

Although I've been a bit slow to get on board with Responsive Design, I finally understand how it works. However, there's one specific issue that has stumped me - something I don't recall ever encountering in my 10 years of website developme ...

PHP having trouble recognizing Ajax POST requests

I am currently working on transferring data from an HTML page to a PHP page. After verifying that the dataString is indeed sending text using console log, it appears as pid=12345 Here is my AJAX code: $.ajax({ type: "POST", url: 'Task2.php&apos ...

How to implement a pop-up dialog box with multiple input boxes using AngularJS?

If you click on the link below: https://material.angularjs.org/latest/demo/dialog You'll notice that the prompt dialog box features only one input field. I'm curious to know if it's possible to customize this using mdDialog to include mult ...

Is there a way to refresh the animation on dougtesting.net?

I'm working with the dougtesting.net library to create a spinning wheel. I've been trying to figure out how to reset the animation once it finishes, but I can't seem to find any information on it. My goal is to completely clear all states so ...

Is it possible to have several users using JW Player simultaneously?

Struggling to incorporate multiple players using JW Player. I've attempted various methods and consulted the documentation, but I can't seem to pinpoint why the code is malfunctioning. Check out the snippets below: In the head section: <scr ...

What steps can I take to have the text extend beyond the background at both the top and bottom edges?

I am attempting to replicate this design using CSS: https://i.sstatic.net/zXInr.png So far, this is what I have achieved: .container{ height: 30px; margin-bottom: 10px; } .redLine{ background-color: red; opacity: 0.5; height: 20px; bor ...

Retrieve Next Element with XPath

I recently started working with XPATH and have a few questions about its capabilities and whether it can achieve what I need. The XML Document structure I am dealing with is as follows: <root> <top id="1"> <item id="1"> < ...

Is it possible to use a single validation rule for multiple fields in JQuery?

I have a question about JQuery validation and custom rules. I am new to this so please bear with me :) When using JQuery validation, if I want a textbox to be required, I can simply add the css class "required" to the element and it will be validated acco ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...

Tips for aligning a Bootstrap container in the middle of the viewport vertically

I'm struggling to center a Bootstrap container vertically in the viewport. You can view my code at http://www.bootply.com/C8vhHTifcE All of my attempts at centering have been unsuccessful. Does anyone have a solution? Just to clarify: I want the co ...

How to retrieve the dimensions of an image for a specified CSS class with Selenium or PIL in Python

I am interested in using Python to determine the size of specific images. Is it possible to automate this process so that I can identify only images with certain classes? I am unfamiliar with PIL. Could I define the CSS class/name/id after specifying the U ...