javascript - How to close accordion element before opening another accordion text -


actually have implemented accordion using bootstrap classes working fine while click on more info.but if click on next accordion text first 1 should close automatically.can 1 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; (i = 0; < acc.length; i++) { acc[i].onclick = function(){     this.classlist.toggle("active");     this.nextelementsibling.classlist.toggle("show");  }  } 

jsfiddle

one approach track expanded accordion e.g:

var currentactive; // track current active accordion. 

and close when 1 expanded,

var toggleaccordionstate = function(accordion) {       accordion.classlist.toggle("active");       accordion.nextelementsibling.classlist.toggle("show"); };  (i = 0; < acc.length; i++) {     acc[i].onclick = function(){         if(currentactive) {                 toggleaccordionstate(currentactive);  //close current accordion.         }         toggleaccordionstate(this);         currentactive = this;     // save current open accordion      } 

see updated fiddle


Comments