简体   繁体   中英

Javascript accordion tabs close

I use an accordion that I want to continue to build. I would like to close all open tabs if I select another tab so that only one tab is open. I am very new to Javascript and am trying to get it right.

Here is my js code:

var acc = document.getElementsByClassName("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";
    }
  });
}

the tabs open on click and close again .. I want to close the open tabs when another tab is open .. only one tab should remain open thants what i want thanks :) – Mr.Murphy

Okay... although I don't know for sure it's that but it looks like:

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";
    }

});

You are adding the onclick to your accordion but then you are using this which should close your currently clicked element. Instead you should create an array and append all opened tabs to it, then close them when a new one opens.

Hope it helps, Elias =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM