Automatically close previous Collapse when a new one is opened in Bootstrap

My Bootstrap Collapse feature is causing an issue where the old collapse remains open when a new one is opened. Is there any way to automatically close the old collapse when a new one is opened?

<div class="my-2">
  <a class="btn btn-success text-start form-control fs-3" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
   <i class="fas fa-minus"></i> 1. PRODAM10 DAMLA NEDİR?
  </a>
<div class="collapse" id="collapseExample">
  <div class="card card-body border-4 fs-4">
    lorem ipsum...
  </div>
</div>
</div>

<div class="my-2">
  <a class="btn btn-success text-start form-control fs-3" data-bs-toggle="collapse" href="#collapseExample2" role="button" aria-expanded="false" aria-controls="collapseExample2">
   <i class="fas fa-minus"></i> 2. Nasıl Etki Eder?
  </a>
<div class="collapse" id="collapseExample2">
  <div class="card card-body border-4 fs-4">
    lorem ipsum...
  </div>
</div>
</div>

Answer №1

When using Bootstrap v4, ensure you utilize an accordion as a parent and include data-parent attribute for the collapsible elements.

For more information, refer to the Bootstrap v4 documentation

<div id="accordion">
    <div className="my-2">
        <a className="btn btn-success text-start form-control fs-3" data-bs-toggle="collapse" href="#collapseExample"
           role="button" aria-expanded="false" aria-controls="collapseExample">
            <i className="fas fa-minus"></i> 1. PRODAM10 DAMLA NEDİR?
        </a>
        <div className="collapse" id="collapseExample" data-parent="#accordion">
            <div className="card card-body border-4 fs-4">
                lorem ipsum...
            </div>
        </div>
    </div>
    
    <div className="my-2">
        <a className="btn btn-success text-start form-control fs-3" data-bs-toggle="collapse" href="#collapseExample2"
           role="button" aria-expanded="false" aria-controls="collapseExample2">
            <i className="fas fa-minus"></i> 2. Nasıl Etki Eder?
        </a>
        <div className="collapse" id="collapseExample2" data-parent="#accordion">
            <div className="card card-body border-4 fs-4">
                lorem ipsum...
            </div>
        </div>
    </div>
</div>

For Bootstrap V5, keep in mind that collapsible and accordion components are distinct. Check out the Bootstrap V5 documentation for more details.

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5d50504b4c4b4d5e4f7f0a110f110d">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16747979626562647766562338263824">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="accordion accordion-flush" id="accordionFlushExample">
    <div class="accordion-item">
        <h2 class="accordion-header" id="flush-headingOne">
            <a className="btn btn-success text-start form-control fs-3 accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" href="#flush-collapseOne"
               role="button" aria-expanded="false" aria-controls="flush-collapseOne">
                <i className="fas fa-minus"></i> 1. PRODAM10 DAMLA NEDİR?
            </a>
        </h2>
        <div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
            <div class="accordion-body">lorem ipsum...</div>
        </div>
    </div>
    <div class="accordion-item">
        <h2 class="accordion-header" id="flush-headingTwo">
            <a className="btn btn-success text-start form-control fs-3 accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" href="#flush-collapseTwo"
               role="button" aria-expanded="false" aria-controls="flush-collapseOne">
                <i className="fas fa-minus"></i> 2. Nasıl Etki Eder?
            </a>
        </h2>
        <div id="flush-collapseTwo" class="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample">
            <div class="accordion-body">lorem ipsum...</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

Is there a way to pre-format a phone number field using jQuery?

Looking to create a phone number text field with a pre-formatted 10-digit structure, like this: |( ) - | allowing users to input numbers and have them fill in automatically: |(804) 479-1832| I came across a helpful script for formatting input d ...

Operating Node SerialPort on a CentOS 6 Linux environment

Hi everyone, I'm a beginner in node.js and I've recently developed an application using node, express, socket, and serialport. I have a weighing scale connected to serialport (COM2) which works perfectly on my Windows localhost. However, when I t ...

Exploring the functionalities of the useState object with mapping techniques

While attempting to convert my class-based component to a functional style, I encountered the following code: const [foo, setFoo] = useState(null); const [roomList, setRoomList] = useState([]); useEffect(() => { setRoomList(props.onFetchRooms(props.to ...

Tips for validating user input within a specific range in React?

I need to restrict user input in an input field to a number range defined by minimum and maximum values. I am working on this functionality using React/Next js. <Input value={tripCoverage} onChange={(e) => { const value = e.target.v ...

Style not being applied to CSS class

When using the 'p' tag by itself, the first CSS rule works fine. However, when I apply the 'article' class with or without the 'p' tag, it does not work. Any thoughts on why that might be? Interestingly, the 'hr' tag ...

How should one go about creating and revoking a blob in React's useEffect function?

Consider this scenario: import { useEffect, useState, type ReactElement } from 'react'; async function getImage(): Promise<Blob> { // Some random async code const res = await fetch('https://picsum.photos/200'); const blob = ...

Test an express + sequelize server using chai-http ping command

Currently facing challenges while setting up tests using Express and Sequelize. The testing framework being used is Mocha + Chai. Initially, only a ping test is being attempted. The code snippet from server.js: const express = require('express&apos ...

How to Use Absolute Positioning in Bootstrap 3.0 to Position Child Divs

I have a div block that needs to always be displayed at the bottom of the section, regardless of whether the section above is empty. The inner div should stay at the bottom of the section, as shown in the attached image. https://i.sstatic.net/cor6k.jpg T ...

Unable to apply the CSS styles on the webpage

I'm having trouble adjusting the CSS for a specific div with the class .cropper inside a component named image-cropper, and I can't figure out why it's not taking effect. Here is an image of the particular div. https://i.sstatic.net/spdJc. ...

Blending synchronous and asynchronous testing with Mocha

There is a function that calculates certain values and informs the user about events using callbacks: function returnAndCallback(callback) { callback(5); // not always called return 3; } Incorporating Mocha and Should.js, a test was created: descri ...

Is there a way to present both Javascript and templates from parallel directories using express?

QUERY: Is there a way to modify the server.js file so that the three.js script in index.html does not display an error message like Cannot GET /node_modules/three/three.js? Code Snippet: index.html <!DOCTYPE html> <html lang="en"> <head&g ...

Uploading files using Angular can result in a null HttpPostedFileBase

When working with Angular in conjunction with MVC, I am facing an issue where the HttpPostedFileBase is coming up as null when attempting to upload a file. This is how the HTML looks: <input type="file" data-ng-model="fileName" onchange="angular.eleme ...

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

The timing of setTimeout within the $.each function does not behave as expected

I am looking to back up a list, delete all items within it, and then append each item one by one with a delay of 1 second between them. This is the approach I have taken: var backup = $('#rGallery').html(); $('#rGallery li').remove(); ...

Javascript problem with closing the browser window in Selenium WebDriver

Here are a couple of inquiries: Firstly: Is there a method to initiate the browser on a specific URL (instead of about:blank) while also setting the history length to 0 when starting on that URL? Secondly: I suspect this question is related to the one me ...

Retrieve data from the controller of the selected element on the subsequent page using AngularJS

Currently, I am in the process of developing an ecommerce platform using angularjs. In my controller, I have a list of various products structured like this: $scope.products = [ {imgLink: 'product1.jpg', name: 'Wingtip Cognac Oxford&apo ...

Create a streaming service that allows for multicasting without prematurely ending the main subject

In my implementation of caching, I am utilizing BehaviorSubject and multicast. The cache stream should begin with an HTTP request and I want the ability to manually trigger a cache refresh by calling next on the subject. While the conventional method of us ...

Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser: I attempted to store the data in a variable with the following code: $http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode& ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

What is the best approach to comply with the EsLint rule "react-hooks/exhaustive-deps" and properly implement componentDidMount using hooks in React with a warning level?

After reviewing the React documentation, it appears that componentDidMount is now implemented using hooks as shown below: useEffect(() => { // your code here }, []) For example, if you wish to make an API call within this hook: useEffect(() => { ...