Is there a way to automatically close other accordions when one is clicked? Additionally, how can the description be hidden when the parent is hidden as

https://i.sstatic.net/jkDoL.pngI have been attempting to switch between the accordion panels; however, when one is clicked, the others should close but this functionality is not working as intended. I need assistance please. In this scenario, there are three categories of creatures: Animals, Birds & Insects, and under each category, there are specific creatures like dogs, cats, peacocks, etc. When a creature is selected, for example a peacock, the corresponding data table should open up. However, clicking on another creature like Kingfisher results in both tables remaining open with the old information still visible. Ideally, only one table should be displayed at a time unless a different creature is chosen. Also, if the Animals section is closed, all related descriptions should also be hidden.

<!DOCTYPE html>
<html>
<head>
  <title>Accordions</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js">
</script>
</head>
... (remaining code)
    
<script>
$(document).ready(function(){
var acc = $(".accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  });
}     
});
</script>

Answer №1

Below is the updated code: You need to add data-parent="#panels" to collapse div and id="panel" to main panel-group div

<!DOCTYPE html>
<html>
<head>
  <title>Accordions</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js">
</script>
</head>
<body>
<style>
.panel-heading.active {
  color: green;
}

#collapseOne2{
margin-left: 3%;
}
.panel-collapse{
margin-left: 3%;
}


.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
   
}
.active:after {
    content: "\2212";
}

.creatures{
padding: 7%;
}

.information{
padding: 3%;
margin-right: 3%;

}
</style>
<div class="container-fluid">
...
... (rest of the code)
...
</script>
</body>
</html>

P.S copy this code and check on your local

Answer №2

Here is a code snippet that you can give a try:

<script>
$(document).ready(function(){
  var elems = $(".accordion");
  
  for (var j = 0; j < elems.length; j++) {
    elems[j].addEventListener("click", function() {
      $(".panel-collapse").removeClass("show");
      $(".panel-heading .panel-title .accordion").removeClass("active");
      this.classList.toggle("active");

      var element = this.nextElementSibling;
      
      if (element.style.maxHeight){
        element.style.maxHeight = null;
      } else {
        element.style.maxHeight = element.scrollHeight + "px";
      }
    });
  }
});
</script>

Answer №3

use this as a model

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
 .bs-example{
        margin: 20px;
          background-color: rgba(215,215,215,1);
          padding: 1em;
    }
<div class="bs-example">
    <div class="panel-group" id="accordion">
        <div class="panel panel-default">
            <div class="panel-heading">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne"> <h4 class="panel-title">
                   Sample Question 1
                </h4></a>
            </div>
            <div id="collapseOne" class="panel-collapse collapse in">
                <div class="panel-body">
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tincidunt ipsum eget nisl accumsan, eu cursus tellus bibendum. Nam et ipsum scelerisque dolor consequat tempor vel vel tortor.</p>
                    <p>Ut finibus facilisis lacus, sit amet porttitor enim mollis sed. Nunc orci magna, iaculis sit amet magna non, tincidunt varius sem.</p>
                </div>
            </div>
        </div>
        <div class="panel panel-default">
            <div class="panel-heading">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo"> <h4 class="panel-title">
                  Example Two
                </h4></a>
            </div>
            <div id="collapseTwo" class="panel-collapse collapse">
                <div class="panel-body">
                   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tincidunt ipsum eget nisl accumsan, eu cursus tellus bibendum. Nam et ipsum scelerisque dolor consequat tempor vel vel tortor.</p>
                    <p>Ut finibus facilisis lacus, sit amet porttitor enim mollis sed. Nunc orci magna, iaculis sit amet magna non, tincidunt varius sem.</p>
                </div>
            </div>
        </div>
       <div class="panel panel-default">
            <div class="panel-heading">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree"> <h4 class="panel-title">
                  Question Number Three
                </h4></a>
            </div>
            <div id="collapseThree" class="panel-collapse collapse">
                <div class="panel-body">
                   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tincidunt ipsum eget nisl accumsan, eu cursus tellus bibendum. Nam et ipsum scelerisque dolor consequat tempor vel vel tortor.</p>
                    <p>Ut finibus facilisis lacus, sit amet porttitor enim mollis sed. Nunc orci magna, iaculis sit amet magna non, tincidunt varius sem.</p>
                </div>
            </div>
        </div>
            </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

Why is the AJAX request not functioning properly after using jQuery's hide method?

It seems that the first AJAX call works fine when I hide the div, but subsequent requests are not going through. a) Clicking on the signup button triggers an AJAX request to display the details. b) Pressing the hide button hides everything within that di ...

After(), when used in conjunction, the slidedown function fails to operate

I have attempted various methods to slide down a newly created element using after() based on examples I found online, but have been unsuccessful. Here are the attempts I made without success. In the following code snippet, the element appears quickly wit ...

Determine element height in Angular 5 by clicking on it

Currently, I am experimenting with determining the height of an element that I click on within a sidebar. The purpose is to display submenus accordingly. Below is the code snippet that I am working on: <li (click)="newsExpanded = !newsExpanded; getMarg ...

The speed at which a DIV moves when dragged with JavaScript mouse events is too fast

I am currently working on moving the #frame-slider-thumb across the image. Initially, I achieved this by monitoring the difference in mouseX position. However, a problem arose where if the thumb was not at 0 to start with, it would jump back to 0. To add ...

Issue encountered while attempting to establish a website on GITHUB PAGES

https://i.sstatic.net/p83ut.png My project was created using Bootstrap, HTML, and CSS. However, when I try to view it on Github pages, only the readme file is displayed and I receive an error message via email. This project holds significant importance fo ...

Get the dropdown values after a successful return from a jQuery AJAX call

When using jQuery AJAX, I retrieve values from the database to populate a dropdown menu. The process involves sending an ID to fetch the level, and then using that level ID and name to obtain related values for the selected level, which are displayed in th ...

Looking to adjust the width of a <div> element dynamically as the browser window resizes using jQuery

I am facing an issue where the width of a <div> should change based on the browser size using jQuery. Below is the code I have written for this functionality. if ($(window).width() > 990 && $(window).width() < 1190) { $("#greybor") ...

Delaying function execution until external scripts are loaded manually using jQuery version 2.1

My current issue arises when performing a browser hard refresh, as it clears the cache and causes my app to be inaccessible once internet connection resumes. To address this, I am looking for a way to manually reload Google's client.js script and rela ...

Sending Django log files via AjaxORTransmitting Django log

After following a solution on Stack Overflow about reading log files in Django from /var/log/gateway, I successfully displayed the file content in the terminal. Here is an example: 2013-05-09T11:15:02.539091+08:00 localhost gateway[5205]: System starting ...

Option list malfunctioning in Safari, Mozilla, as well as Chrome browsers

I encountered some issues while working on the front-end of my web app. Here are a few problems: I need to truncate text if it's too long, so I use the following CSS: .suggestion-box-text { white-space: nowrap; overflow: hidden; text-overfl ...

Customizing CSS input file for Firefox (also compatible with Chrome)

Currently, I am developing an upload page that does not allow the use of jquery and bootstrap. For Chrome, I have implemented the following CSS code to address my issue: .btn-file-upload{ width: 200px; position:relative; height: 40px; } .btn- ...

Encountering a problem in vue.js: "The instance is referencing 'step1_category' which is not defined as a property or method during render"

I encountered an error that says, "Property or method 'step1_category' is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializin ...

Is it possible to utilize NPOI/C# to convert an HTML table into an xls/xlsx file?

My primary objective is to dynamically generate an XLS file containing an HTML table on the server side in my .NET application. The data model of my HTML table is quite intricate, but I have successfully created the model using dotliquid for a different pu ...

Tips for preventing a div from scrolling beyond the header with the use of position: sticky?

My header utilizes the CSS property position: sticky; to stick at the top of the page. However, this creates a gap between the header and the top of the page that I intentionally left there. As you scroll down, you can see the content div moving under and ...

Prolonging PHP session duration with the help of Ajax

As a web page owner, I encountered issues with users losing data due to session time out on my huge form. After researching solutions, I came across this helpful resource on preventing PHP Session expiration for inactive users. To address this problem, I ...

Record the clicks registered within an external jQuery UI modal window

I have a jQuery UI dialog window that contains thumbnail images. When an image is clicked, I want to retrieve the id of that specific image. I believe using data attributes can help me achieve this easily. However, I'm facing an issue where I am unab ...

Experiencing a problem parsing a JSON string using jQuery token input functionality

In a recent project, I implemented jquery token input with the following initialization method. $(document).ready(function(){ var defaultOptions = { searchDelay: 500, minChars: 3, }; $(' ...

Looking to implement a scroll bar in your PhoneGap mobile app for Android?

Encountering an issue with my Android PhoneGap mobile website application. I have implemented a scroll bar in the application which works perfectly on PC. However, when testing on an Android device (mobile phone), the scroll bar does not enable. ...

What is the best way to add ajax data to a page without duplicating

When a user selects an option from the drop-down menu, I am attempting to add new data to my select tag. obj.prototype.getText=function(){ codes.... call ajax.... ajax.callback=function(data){ $('#option' ...

Ways to access dropdown menu without causing header to move using jQuery

Greetings everyone, I am currently working on a dropdown language selection feature for my website. The issue I am facing is that when I click on the language dropdown in the header, it causes the height of the header to shift. $('.language- ...