user6728960 user6728960 - 3 months ago 14
CSS Question

How to close accordion element before opening another accordion text

Actually i have implemented Accordion using bootstrap classes It is working fine while we click on More Info.But If i click on Next accordion text the first one should close automatically.Can any one help me this.Thanks In advance.

HTML:

<div class="accordion" >More Info</div>
<div class="panel">
<p>
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</p>
</div>
<div class="accordion" >More Info</div>
<div class="panel">
<p>
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</p>
</div>


CSS:

div.panel {
padding: 0 18px;
display: none;
background-color: white;
border: 1px solid #d4d4d4;
}

div.panel.show {
display: block;
color: #2b3034;
font-size: 12px;
font-family: Roboto,sans-serif;
margin-left: -18px;
border-radius: 0px;
width: 778px;
margin-top: 16px;
background: #ffffff;
margin-bottom: -17px;
}


Javascript:

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}


JSFiddle

Answer

One approach could be to track the previously expanded accordion e.g:

var currentActive; // track the current active accordion.

and close it when another one is expanded,

var toggleAccordionState = function(accordion) {
      accordion.classList.toggle("active");
      accordion.nextElementSibling.classList.toggle("show");
};

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        if(currentActive) {
                toggleAccordionState(currentActive);  //Close the current accordion.
        }
        toggleAccordionState(this);
        currentActive = this;     // Save the current open accordion   
  }

see the updated fiddle