I'm totally scratching my head on this one so I apologize if it's a simple fix. I'm using Accordion categories to expand and collapse sections by either clicking the same section again to collapse it or clicking another section to collapse the other one that's open.
If the user goes to close an open section by clicking on the open section, the section doesn't reset to the default background color and symbol. By default the background color is set to #00000042 and a + on the right. When expanded it changes to #71717171 and a - on the right. When clicked again the background remains at #71717171 and the symbol stays as -. Would like the background to go back to #00000042 and a + symbol when collapsed.
It works fine if the category is closed by clicking another one, but if you want to have the one that is opened to be closed by clicking on it, it won't work.
Just not sure what will allow the category when collapsed by clicking on the one that is open to go back to the original background color and + on the right.
Here is what I have:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
let active = document.querySelectorAll(".accordion-div .accordion.active");
for (let j = 0; j < active.length; j++) {
active[j].classList.remove("active");
active[j].nextElementSibling.style.maxHeight = null;
}
this.classList.toggle("active");
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
.accordion {
color: #fff;
background-color: #00000042;
cursor: pointer;
padding: 2px 10px 5px 10px;
margin-top: 5px;
width: 100%;
border: 1px solid #00000042;
text-align: left;
outline: none;
transition: 0.4s;
height: 20px;
}
.active,
.accordion:hover {
background-color: #71717171;
border: 1px solid #00000042;
}
.accordion:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
<div class="accordion-div">
<button class="accordion">Category 1</button>
<div class="panel">category text description</div>
<button class="accordion">Category 2</button>
<div class="panel">category text description</div>
<button class="accordion">Category 3</button>
<div class="panel">category text description</div>
</div>
When checking for maxHeight of the content, toggle the active class on the current element.
if (panel.style.maxHeight){
this.classList.toggle("active");
panel.style.maxHeight = null;
}