ReactJS how to prevent accordion from collapsing automatically

My custom accordion layout for the features needed in the site I am building is not working well with Jquery. How can I modify it to collapse properly? Specifically, I want it so that when I open number 2, number 1 will automatically close.

I've tried using the common jquery methods found online, but they don't seem to be effective. I've been staring at my screen with a puzzled look for an hour now.

<div id="accordion">
<div className="GreyCircle top" />
<div className="Item" >
    <div className="DestinationMarkerGreen active" >1</div>
    <div className="square" />
    <div className="Content" >
        <div className="card">
            <div className="card-header" id="heading1" data-toggle="collapse" data-target="#collapse1" aria-expanded="true" aria-controls="collapse1">
                <h4>Bristol</h4>
                <p>England, United Kingdom</p>
            </div>
            <div id="collapse1" className="collapse show in accordionItem" aria-labelledby="heading1" data-parent="#accordion">
                <div className="card-body">
                              Include your code here.
                            </div>
            </div>
        </div>
    </div>
</div>
<div className="Item" >
    <div className="DestinationMarkerGreen" >2</div>
    <div className="square" />
    <div className="Content" >
        <div className="card">
            <div className="card-header" id="heading2" data-toggle="collapse" data-target="#collapse2" aria-expanded="true" aria-controls="collapse2">
                <h4>Bristol</h4>
                <p>England, United Kingdom</p>
            </div>
            <div id="collapse2" className="collapse  accordionItem" aria-labelledby="heading2" data-parent="#accordion">
                <div className="card-body">
                              Include your code here.
                            </div>
            </div>
        </div>
    </div>
</div>
<div className="Item" >
    <div className="DestinationMarkerGreen" >3</div>
    <div className="square" />
    <div className="Content" >
        <div className="card">
            <div className="card-header" id="heading3" data-toggle="collapse" data-target="#collapse3" aria-expanded="true" aria-controls="collapse3">
                <h4>Bristol</h4>
                <p>England, United Kingdom</p>
            </div>
            <div id="collapse3" className="collapse show accordionItem" aria-labelledby="heading3" data-parent="#accordion">
                <div className="card-body">
                              Include your code here.
                            </div>
            </div>
        </div>
    </div>
</div>

Here is what the image should look like

Answer №1

$('#accordion').on('show.bs.collapse', function() {
  $('#accordion .in').collapse('hide');
});

This solution resolved the problem I was facing.

Answer №2

Have you considered using the jQuery UI Accordion plugin available at https://jqueryui.com/accordion/? If you're unfamiliar with jQuery, it's best to utilize tools like this rather than attempting to build your own solution from scratch. :)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Accordion - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#accordion" ).accordion();
  } );
  </script>
</head>
<body>

<div id="accordion">
  <h3>Section 1</h3>
  <div>
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit...
    </p>
  </div>
  <h3>Section 2</h3>
  <div>
    <p>
    Duis auctor ultricies mauris, vel varius ligula tempus non.
    </p>
  </div>
  <h3>Section 3</h3>
  <div>
    <p>
    Quisque efficitur felis magna, nec volutpat justo blandit at...
    </p>
    <ul>
      <li>List item one</li>
      <li>List item two</li>
      <li>List item three</li>
    </ul>
  </div>
  <h3>Section 4</h3>
  <div>
    <p>
    Curabitur fermentum enim vitae leo congue mattis.
    </p>
    <p>
    Vivamus accumsan odio eu purus molestie dapibus.
    </p>
  </div>
</div>

</body>
</html>

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

The plugin function cannot be executed unless inside the document.ready event

Utilizing jquery and JSF to construct the pages of my application includes binding functions after every ajax request, such as masks and form messages. However, I am encountering an issue where I cannot access the plugins outside of $(function(). (functio ...

Some CSS styles are not displaying correctly within an iframe

Let me start by clarifying that I am not looking to add extra CSS to the contents of an iframe from the parent document. My issue lies with a document that normally displays correctly but experiences styling issues when shown in an iframe. Whenever I searc ...

Hey there, I'm looking to automatically delete new users from my mongoDB atlas database if they haven't verified their phone number within 2 minutes. I believe using the TTL feature would be

Database Schema In my User schema, the field isVerified is initially saved as false. The user enters their phone number, receives a verification token via SMS, and both the token and number are saved in the database. Once the user enters the verification ...

Creating dynamic charts in Javascript using Firebase

My dad recently asked me to enhance our motor home by integrating an Arduino with Firebase to monitor the water and propane tanks. He's hoping to be able to check tank levels from his phone so he can see when they need refilling. I've successful ...

Having trouble getting items to align properly in Bootstrap

As a student, I am struggling with my development skills while attempting to create a personal website. I am encountering difficulty aligning items on my rows in bootstrap. Here is what I am trying to accomplish: 1. However, I am currently stuck at this po ...

What are the steps for configuring i18n translated URL paths in Next.js?

I have successfully implemented multi-language support on my website using Next.js i18n-routing. When I create a file in /pages/about.js, the URLs are generated based on my locale settings: EN -> /about DE -> /de/about ES -> /es/about Everything ...

Creating a Star Rating System Using HTML and CSS

Looking for help with implementing a Star rating Feedback on articles in Visualforce page. Came across some code that seems to fit the bill but facing issues with getting it to work when placed in a file and executed, particularly in Firefox. Any assistanc ...

The ng-route feature seems to be malfunctioning and I am unable to identify the error, as no information is being displayed in the console

Here is the code in my boot.php file where I have set up the links <ul class="nav nav-pills nav-stacked"> <li role="presentation"><a href="#/valley">Valley</a></li> <li role="presentation"><a href="#/beach"> ...

Escaping the setTimeout loop

I'm struggling to find a solution for breaking out of a setTimeout loop. for (var i = 0; i < 75; i++) { setTimeout(function (i) { return function () { console.log("turn no. " + i); if (table.game.playerWon) { con ...

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...

Creating a JQuery Dialog Box Integrated with DataTable()

I need some assistance with a problem I'm encountering while using Asp.net and JQuery UI 1.9.2. On my form, I have a textbox and a search button. Upon clicking the button, I query the database on the server side and store all the results in a Gridview ...

Locate an element that is nested within a "concat(" XPATH using Selenium

Embarking on my inaugural project as a Python developer, I am currently in the process of web scraping a retail website. The challenge lies in the fact that the site features infinite scrolling functionality, although at times instead of triggering the inf ...

Issue with Vuetify carousel not resizing to fit the entire width and height

I am looking to create a carousel that spans the entire width and height of a viewport in my Vue.js 2 project using Vuetify. Below is the code I have so far: <head> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500, ...

What are the reasons for the default router in Next Js not functioning properly?

My default router is not functioning properly even though I have used the correct folder structure in version 13.5.4 of Next Js. I created a new project using the command npx create-next-app@latest project name. Within the App folder, I created a folder c ...

Developing with Phonegap Build: A Guided Process

With all the conflicting information available, I am seeking clarity on this topic. Objective: To create and enhance a Phonegap app using Phonegap Build. 1) My preference is to utilize Phonegap Build without needing to install Android and iOS SDKs. 2) I ...

Issues with Node AssertionErrors cause failures to be silent and prevent proper error output

I am facing an issue with a particular method in my code. The code snippet is as follows: console.log('Trouble spot here') assert(false) console.log('Will this show up?') Upon running this code within my application, the followi ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

Mongoose virtual population allows you to fetch related fields

When attempting to utilize virtual populate between two models that I've created, the goal is to retrieve all reviews with the tour id and display them alongside the corresponding tour. This is achieved by using query findById() to specifically show o ...

Vue.js is not properly synchronizing props in a child component when the parent component is updating the property

When it comes to communication between components, my structure looks something like this: <div id=chat-box> <div class="wrapper"> <div> <chat-header></chat-header> <message-container :chat="chat"></message ...

Why is my custom function failing to operate on an array?

My function is created to organize and remove duplicates from a provided array. Below is an excerpt of the code: Bubble Sort - function organize(postsCollection, type, direction){ let target = postsCollection[0][type]; let swapp = false, ...