Bootstrap 4 Collapse - Ensuring that collapsed elements remain open when expanding other accordions

Can someone help me figure out how to keep an element open when another one is opened? Here is an example: https://getbootstrap.com/docs/4.0/components/collapse/

<div id="exampleAccordion" data-children=".item">
   <div class="item">
      <a data-toggle="collapse" data-parent="#exampleAccordion" href="#exampleAccordion1" aria-expanded="true" aria-controls="exampleAccordion1">
  Toggle item
      </a>
      <div id="exampleAccordion1" class="collapse show" role="tabpanel">
        <p class="mb-3">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium lorem non vestibulum scelerisque. Proin a vestibulum sem, eget tristique massa. Aliquam lacinia rhoncus nibh quis ornare.
        </p>
      </div>
   </div>


<div class="item">
   <a data-toggle="collapse" data-parent="#exampleAccordion" href="#exampleAccordion2" aria-expanded="false" aria-controls="exampleAccordion2">
  Toggle item 2
   </a>
   <div id="exampleAccordion2" class="collapse" role="tabpanel">
      <p class="mb-3">
    Donec at ipsum dignissim, rutrum turpis scelerisque, tristique lectus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus nec dui turpis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
      </p>
   </div>
</div>
</div>

Answer №1

Give this a try, it should do the trick,

HTML
-----
<div class="container">
  <div class="accordion-option">
    <h3 class="title">Lorem Ipsum</h3>
    <a href="javascript:void(0)" class="toggle-accordion active" accordion-id="#accordion"></a>
  </div>
  <div class="clearfix"></div>
  <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingOne">
        <h4 class="panel-title">
        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
        <div class="panel-body">
         content 1
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingTwo">
        <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
      </div>
      <div id="collapseTwo" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingTwo">
        <div class="panel-body">
          content 2
        </div>
      </div>
    </div>
    <div class="panel panel-default">      
      </div>
    </div>
  </div>
</div>

CSS:
----
body {
  color: #6a6c6f;
  background-color: #f1f3f6;
  margin-top: 30px;
}

.container {
  max-width: 960px;
}

.panel-default>.panel-heading {
  color: #333;
  background-color: #fff;
  border-color: #e4e5e7;
  padding: 0;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.panel-default>.panel-heading a {
  display: block;
  padding: 10px 15px;
}

.panel-default>.panel-heading a:after {
  content: "";
  position: relative;
  top: 1px;
  display: inline-block;
  font-family: 'Glyphicons Halflings';
  font-style: normal;
  font-weight: 400;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  float: right;
  transition: transform .25s linear;
  -webkit-transition: -webkit-transform .25s linear;
}

.panel-default>.panel-heading a[aria-expanded="true"] {
  background-color: #eee;
}

.panel-default>.panel-heading a[aria-expanded="true"]:after {
  content: "\2212";
  -webkit-transform: rotate(180deg);
  transform: rotate(180deg);
}

.panel-default>.panel-heading a[aria-expanded="false"]:after {
  content: "\002b";
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}

.accordion-option {
  width: 100%;
  float: left;
  clear: both;
  margin: 15px 0;
}

.accordion-option .title {
  font-size: 20px;
  font-weight: bold;
  float: left;
  padding: 0;
  margin: 0;
}

.accordion-option .toggle-accordion {
  float: right;
  font-size: 16px;
  color: #6a6c6f;
}

.accordion-option .toggle-accordion:before {
  content: "Expand All";
}

.accordion-option .toggle-accordion.active:before {
  content: "Collapse All";
}

Javascript:
-----------
$(document).ready(function() {

  $(".toggle-accordion").on("click", function() {
    var accordionId = $(this).attr("accordion-id"),
      numPanelOpen = $(accordionId + ' .collapse.in').length;

    $(this).toggleClass("active");

    if (numPanelOpen == 0) {
      openAllPanels(accordionId);
    } else {
      closeAllPanels(accordionId);
    }
  })

  openAllPanels = function(aId) {
    console.log("setAllPanelOpen");
    $(aId + ' .panel-collapse:not(".in")').collapse('show');
  }
  closeAllPanels = function(aId) {
    console.log("setAllPanelclose");
    $(aId + ' .panel-collapse.in').collapse('hide');
  }

});

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

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

Is it possible to use JavaScript to click on a particular point or element within a canvas?

Is there a way to trigger a click at a specific point on a canvas without direct access to the code that generates it? I've attempted using coordinates, but haven't had any success. Any alternative suggestions would be appreciated. UPDATE: To pr ...

I'm looking to customize my d3.js Bar Graph by changing the color of each bar individually and adding a Scale for them. How can I

I am currently working on constructing a graph that illustrates the data for the Amount of Resources utilized Per Project by creating a bar graph. I am aiming to customize the colors of the bars so that each one has its own unique color. Currently, the col ...

Tips for enhancing the transition effect of animated gifs on a webpage using JavaScript

In my code, I have an interval set to run every seven seconds. Within this interval, there are two gifs that each last for seven seconds. My goal is to display one of the gifs in a div (referred to as "face") based on certain conditions - for example, if t ...

mongojs implementation that allows for asynchronous query execution without blocking

Forgive me for asking what may seem like a silly question, but I am struggling to make this work. Currently, as part of my learning journey with node.js and mongojs, I have encountered the following issue: Below is my server.js file server.get("/", funct ...

Ways to bypass mongoose schema validation while making an update request in the API

In my model, one of the fields is specified as providerID: { type: Number, required: true, unique: true }. The providerID is a unique number that is assigned when inserting provider details for the first time. There are situations where I need to update ...

Django enables anonymous Ajax requests to reach a Generic View

Here is the current progress I have made: from django.views.generic import View from django.views.decorators.csrf import csrf_exempt class ConfigurationView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(Configurati ...

Applying flexbox to create a visually appealing design

Is there a way to achieve this layout using flexbox without relying on grid due to limited support in IE11? I want to be able to easily add or remove small divs without adding more containers. To see the desired layout, check out this image: Desired Layou ...

Tips for positioning an image, text, and button horizontally without resorting to tables

Does anyone know how to align a movie poster image, description text, and add to cart button on the same line? The text must be centered aligned without wrapping around the button or image, just like in this example. Currently, my setup looks like this. T ...

Three.js experiences a memory leak issue

We are currently working on a single page app where users can switch between multiple Three.js apps. However, we have observed a continuous increase in memory usage by the tab. There is no memory leakage in our app and it appears that Three.js variables ar ...

Display function not functioning properly following AJAX request

I'm working on a functionality where I want to initially hide a table when the page loads, and then display it with the results when a form is submitted using Ajax. The issue I'm facing is that the code refreshes the page and sets the table back ...

Is it necessary to send form data back with Express, or is there an alternative solution?

I am facing a simple problem with my handlers for /login get and post requests. Here is the code: loginRender(req, res) { let options = { title: 'Login', layout: 'auth.hbs' } res.render('login', options) } logi ...

Struggling to repair the unresponsive on-click event even after thorough debugging efforts

i am working on a project where i have to create a datatable, but I am facing an issue with the edit event not firing on click. Even after debugging, it is not pointing towards any error. function GetLoginData() { $.ajax({ url: '/LoginMas ...

What is the best way to keep an HTML element visible on the page while it remains within the boundaries of another HTML object?

On my webpage, I have a selection of reports available. Currently, there are 4 sizable buttons located on the right-hand side for viewing, adding, editing, or deleting a report. However, there have been complaints from users who find it inconvenient to scr ...

Finding the correct closing tag in HTML can be accomplished using an algorithm

Currently working on my custom HTML parser in JAVA and have completed the lexer. Now diving into coding the parser to create a DOM tree and ensure the proper construction of my HTML. For example, understanding that an img tag is considered a void tag as p ...

Disabling pointer-events on material-ui textField input is ineffective

I have a material-ui textField input and I want to prevent the user from entering text by setting the css to pointer-events: none. However, this method does not work as expected. While I am aware that I can use the disabled={true} flag to disable the inpu ...

Discover the steps to dynamically alter the inclusion of the Bootstrap CSS file within an Angular project

I manage a multi-language website in both English (EN) and Arabic (AR). Currently, I am utilizing Bootstrap CSS from a CDN and adjusting the CDN link based on the selected language. index.html <!DOCTYPE html> <html lang="en"> <h ...

"Put Jest to the test by running it with the Express

Currently, I am in the process of learning how to build an API with TypeScript and experimenting with testing it using the Jest framework. When utilizing a basic Express application like app = express() supertest(app) everything works smoothly. However, ...

Revamp selected bootstrap attribute

Imagine a scenario where there is: @media (min-width: 576px) { #projects-edit-middle-column .equal-columns-wrapper .equal-columns { width: 50%; padding-right: 25px; } } This is being utilized within a container: <div class="equal-columns ...

Moving up stacked columns with bootstrap or any other CSS technique

Is there a way to make column [3] move up if column [2] is taller than column [1]? [1][2] [3][4] Check out this bootply example of the layout : http://www.bootply.com/KbAf8UOk9c Currently, there is empty space between column [1] and [3] that I would li ...